在mybatis中配置文件主要分为两类,核心配置文件和映射配置文件。核心配置文件主要配置mybatis一些基础组件和加载资源,核心配置文件中的元素常常能影响mybatis的整个运行过程,比如<settings>节点中的内容;映射配置文件主要配置了sql语句和类型转换相关的一些信息,也就是说映射文件指导着MyBatis如何进行数据库增删改查,映射配置文件通常和Mapper接口相对应,当然采用注解开发时候只有Mapper接口没有映射配置文件。
一、核心配置文件
相关的节点信息
1.properties是一个配置属性的元素
2.settings设置,mybatis最为复杂的配置也是最重要的,会改变mybatis运行时候的行为
3.typeAliases别名(在TypeAliasRegistry中可以看到mybatis提供了许多的系统别名)
4.typeHandlers 类型处理器(比如在预处理语句中设置一个参数或者从结果集中获取一个参数时候,都会用到类型处理器,在TypeHandlerRegistry中定义了很多的类型处理器)
5.objectFactory 对象工厂(myabtis在构建一个结果返回的时候,会使用一个ObjectFactory去构建pojo)
6.plugins 插件
7.environments 环境变量
environment 环境变量
transactionManager 事务管理器
dataSource 数据源
databaseIdProvider 数据库厂商标识
8.mappers 映射器
二、映射配置文件
相关的节点信息
1.cache –命名空间的二级缓存配置
2.cache-ref – 其他命名空间缓存配置的引用
3.resultMap – 自定义结果集映射
4.sql –抽取可重用语句块
5.insert – 映射插入语句
6.update – 映射更新语句
7.delete – 映射删除语句
8.select – 映射查询语句
三、映射配置文件相关节点简单使用
1.insert、update、delete节点
insert、update、delete分别代表着插入、更新、删除操作,三个节点的使用方式差不同,不同的是SQL语句的拼写不同。在xxxMapper.xml中配置如下:
<!--插入-->
<insert id="insert">
insert into user(user_name,user_password
,user_email,user_info,head_img,create_time)
values(#{userName},#{userPassword}
,#{userEmail},#{userInfo},#{headImg},#{createTime,jdbcType=TIMESTAMP})
</insert>
<!--更新-->
<update id="update">
update user set
user_name=#{userName},
user_password=#{userPassword}
where id=#{id}
</update>
<!--删除-->
<delete id="delete">
delete from user where id=#{id}
</delete>
2.select节点
- select节点来定义查询操作,是mybatis映射配置文件中使用比较多的节点,使用该节点,能完成各种复杂的查询工作,该节点主要参数说明:
1.Id:唯一标识符。
用来引用这条语句,需要和接口的方法名一致
2.parameterType:参数类型。
可以不传,MyBatis会根据TypeHandler自动推断
3.resultType:返回值类型。
别名或者全类名,如果返回的是集合,定义集合中元素的类型。不能和resultMap同时使用
4.resultMap:返回类型引用resultMap节点中的类型
- select节点案例说明:
<!--通过id查询user对象-->
<!--使用别名-->
<resultMap id="userMap" type="User">
<id property="id" column="id" />
<result property="userName" column="user_name" />
<result property="userPassword" column="user_password" />
<result property="userEmail" column="user_email" />
<result property="headImg" column="head_url" />
<result property="createTime" column="create_time"
jdbcType="TIMESTAMP" />
</resultMap>
<select id="selectById" resultMap="userMap">
select * from user where
id=#{id}
</select>
3.resultMap节点
- resultMap节点是mybatis中最为复杂的节点,也是使用比较多的节点。
resultMap节点实现方式有两种情况:
1.默认的自定映射
(1)要求是列名和javaBean属性名一致
(2)但是数据库字段命名规范,POJO属性符合驼峰命名法,如A_COLUMN->aColumn,我们可以开启
自动驼峰命名规则映射功能,mapUnderscoreToCamelCase=true。
2.自定义 resultMap , 实现高级映射,一些比较重要的属性如下
(1)association一对一级联
(2)collection一对多级联
(3)discriminator鉴别器级联
...等等
- 关于resultMap节点的内容比较多,放在关联查询部分在重点讲述,这边只是做个简单的介绍
4.sql节点
sql作用主要是抽取可重用语句块,在其他insert、update、delect、select等节点需要的时候插入语句块就完成了语句块的复用。具体案例:
<sql id="Base_Column_List">
id, user_name, user_password, user_email, user_info, head_img, create_time
</sql>
<!-- 增加自己增加的方法 -->
<select id="findAllUser" resultMap="BaseResultMap">
select
<!--通过include 属性插入复用的代码块-->
<include refid="Base_Column_List"></include>
from user
</select>
5.Cache和Cache-ref节点
这两个节点是关于缓存方面的,这里不过多介绍,等使用到缓存时候在进行详细的说明。