JavaWeb-- MyBatis
MyBatis 核心文件配置
遵守标签顺序
environments环境变量
encironments: 配置数据库连接环境信息,可以配置多个encironment(数据源),通过fefault属性调用不同的encironment
typeAllases
<!-- 别名代替包名找到里面的类-->
<typeAliases>
<!-- 将pojo下所有文件起的别名 即各自的类名且不再区分大小写 -->
<package name="com.itheima.pojo"/>
</typeAliases>
配置文件完成增删改查
需要完成的功能
插件MybatisX
提高效率的原因加速啦SQL与Mapper的映射速度
1.查询所有的数据
1.编写Mapper
2. 编写SQL映射文件(直接复制之前的)
3.执行
public void testSelectAll() throws IOException {
// 1. 获取SqlSession对象
/* String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
String resource = "mybatis-config.xml";
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
// 2.获取 SqlSess 对象 用她来执行sql语句
SqlSession sqlSession = sessionFactory.openSession();
// 3.通过SqlSession获取Mapper接口的代理对象
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4. 通过mapper对象执行BrandMapper.class里面的方法
List<Brand> brands = mapper.selectAll();
System.out.println(brands);
// 5.释放资源
sqlSession.close();
}
4.运行结果
因为java里面采用的时驼峰的方式和数据库内部的 _方式不同所以会出现查询的某些为null。
解决方案
1.起别名
1.2 sql片端
<!-- 数据路里面的字段名称和实体类的属性不一样无法自动封装
* 起别名:将数据库的属性名起别名为属性名
*缺点:每次都需要写特别长的代码
* sql片段
*
-->
<sql id="brand_colum">id
, brand_name as brandName, company_name as companyName, ordered, description, status</sql>
<select id="selectAll" resultType="Brand">
select
<include refid="brand_colum"/>
from tb_brand;
</select>
2.resultMap
<!-- *resultMap
*1.创建映射与package里面的brand形成映射,设置里面的属性<id>主键 <result> 一般属性 类似于做了一个属性与字段之间的映射
*2.将<select>里面的resultType改为resultMap-->
<resultMap id="brandResultMap" type="brand">
<!-- 主键的映射 <id></id>-->
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
运行结果