相关文章
Mybatis 数据源和数据库连接池源码解析(DataSource)
Mybatis Mapper 接口源码解析(binding包)
前言
在上篇文章 Mybatis 解析 SQL 源码分析一 介绍了 Maper.xml 配置文件的解析,但是没有解析 resultMap 节点,因为该解析比较复杂,也比较难理解,所有单独拿出来进行解析。
在使用 Mybatis 的时候,都会使用resultMap节点来绑定列与bean属性的对应关系,但是一般就只会使用其简单的属性,他还有一些比较复杂的属性可以实现一些高级的功能,在没查看源码之前,我也只会简单的使用,很多高级的用法都没有使用过,通过这次学习,希望能在工作使用,能够写出简洁高效的SQL。
resultMap的定义
先来看看 resultMap 节点的官方定义:
简单的使用:
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="user_name"/>
<result property="password" column="hashed_password"/>
</resultMap>
会把列名和属性名进行绑定,该节点一共有 4 个属性:
1. id :表示该 resultMap,共其他的语句调用
2. type:表示其对于的pojo类型,可以使用别名,也可以使用全限定类名
3. autoMapping:如果设置这个属性,MyBatis将会为这个ResultMap开启或者关闭自动映射。这个属性会覆盖全局的属性 autoMappingBehavior。默认值为:unset。
4. extends:继承,一个 resultMap 可以继承另一个 resultMap,这个属性是不是没有用过 ? ^^
接下来看下它可以有哪些子节点:
- constructor – 用于注入结果到构造方法中
- id – 标识ID列
- result – 表示一般列
- association – 关联查询
- collection – 查询集合
- discriminator – 鉴别器:mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
constructor
在查询数据库得到数据后,会把对应列的值赋值给javabean对象对应的属性,默认情况下mybatis会调用实体类的无参构造方法创建一个实体类,然后再给各个属性赋值,如果没有构造方法的时候,可以使用 constructor 节点进行绑定,如现有如下的构造方法:
public Person(int id, String name, String job, int age) {
this.id = id;
this.name = name;
this.job = job;
this.age = age;
}
则,可以使用 constructor 节点进行绑定:
<resultMap id="queryPersonMap" type="mybatis.pojo.Person" >
<constructor>
<idArg column="id" javaType="int"/>
<arg column="name" javaType="string" />
<arg column="job" javaType="string" />
<arg column="age" javaType="int" />
</constructor>
</resultMap>
association
关联查询,在级联中有一对一、一对多、多对多等关系,association主要是用来解决一对一关系的,association 可以有多种使用方式:
比如现在有一个 Person 类,它有一个 Address 属性,关联 Address 对象:
public class Person implements Serializable {
private int id;
private String name;
private String job;
private int age;
private Address address;
}
public class Address {
private int id;
private String name;
private long number;
}
关联查询方式一:
<resultMap id="queryPersonMap" type="mybatis.p