这篇文章主要讲述Mybatis鉴别器discriminator和延迟加载的用法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
什么是鉴别器?
mybatis可以使用discriminator判断某列的值,然后根据某列的值改变封装行为
代码示例
这里我们以一个一对一的联查来使用鉴别器和延迟加载来完成一些特定要求。
Employee类
此处省略get,set方法等。。
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender; //性别
private Department dept; //部门
}
Department 类
public class Department {
private Integer id;
private String departmentName; //部门名称
}
接口类
public interface EmployeeMapperPlus {
public Employee getEmpByIdStep(Integer id);
}
现在我们要实现以下:
如果查出的是女生:就把部门信息查询出来,否则不查询;
如果是男生,把last_name这一列的值赋值给email;
xml映射文件
<resultMap type="com.gzl.mybatis.bean.Employee" id="MyEmpDis">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!--
column:指定判定的列名
javaType:列值对应的java类型 -->
<discriminator javaType="string" column="gender">
<!--女生 resultType:指定封装的结果类型;不能缺少。/resultMap-->
<case value="0" resultType="com.gzl.mybatis.bean.Employee">
<association property="dept"
select="getDeptById"
column="d_id">
</association>
</case>
<!--男生 ;如果是男生,把last_name这一列的值赋值给email; -->
<case value="1" resultType="com.gzl.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="last_name" property="email"/>
<result column="gender" property="gender"/>
</case>
</discriminator>
</resultMap>
<select id="getEmpByIdStep" resultMap="MyEmpDis">
select * from tbl_employee where id=#{id}
</select>
<select id="getDeptById" resultType="com.gzl.mybatis.bean.Department">
select id,dept_name departmentName from tbl_dept where id=#{id}
</select>
测试:
这是测试数据,这里我们拿id为1的和为3的来测试,gender 属性1是男的,2是女的
先看1的执行结果。这里可以看出他并没有去查询部门表,所以这里输出结果为null,也就是他经过case之后没有执行这个,并且他把lastname赋值给了email
再看看id为3的时候的结果,他已经把部门表封装到了主表当中。
总结
延迟加载也就是把多表联查给拆分了出来,这样可以做到用的时候查,不用的时候不查。
鉴别器可以帮助我们完成一些特定的判断。
根据需求合理使用Mybatis给我们提供现有的功能。