mybatis级联查询,分步查询和延迟加载
Posted 猫一只咪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis级联查询,分步查询和延迟加载相关的知识,希望对你有一定的参考价值。
级联查询:
1.Employee表:
id;lastName;email; gender;d_id(外键关联Department的ID)
2.Department表:
id;deptName;
3。首先,为了级联,Employee(javaBean)如下:
private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;
Department(javaBean)如下:
private Integer id;
private String deptName;
4.级联三种方式:
4.1:新建resultMap (resultMap的id是select标签的resultMap名字)
非Employee表的列通过<result column="数据库列名" property="javaBean中该类的名称.类属性"/>
<resultMap type="com.mybatis.bean.Employee" id="myDifEmployee">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<result column="d_id" property="dept.id"/>
<result column="dept_name" property="dept.deptName"/>
</resultMap>
<select id="getEmpAndDept" resultMap="myDifEmployee">
select e.id id, e.last_name last_name, e.gender gender, e.d_id d_id, d.id did, d.dept_name dept_name from tbl_employee as e,tbl_department as d where e.d_id = d.id and e.id=#{id}
</select>
4.2:
<!-- association级联 <association property="javaBean中该类的名称" javaType="类类型地址">-->
<resultMap type="com.mybatis.bean.Employee" id="myDifEmployee2">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<association property="dept" javaType="com.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<select id="getEmpAndDept" resultMap="myDifEmployee2">
select e.id id, e.last_name last_name, e.gender gender, e.d_id d_id, d.id did, d.dept_name dept_name from tbl_employee as e,tbl_department as d where e.d_id = d.id and e.id=#{id}
</select>
4.3:分步查询
<!-- association分步
select:表明当前属性是调用select指定方法查出的结果 是XXXMapper.xml中namespace。方法名
column;指定将哪一列的值传给这个方法
-->
<resultMap type="com.mybatis.bean.Employee" id="myEmpByIdStep">
<id column="id" property="id"/>
<result column="gender" property="gender"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<association property="dept" select="com.mybatis.dao.DepartmentMapper.getDeptById" column="d_id">
</association>
</resultMap>
<select id="getEmpByIdStep" resultMap="myEmpByIdStep">
select * from tbl_employee where id = #{id}
</select>
5.延迟加载
延迟加载的以上是如果需要的仅仅是tbl_employee 表的值,那么sql语句就不查询tbl_department 。
如果需要tbl_department ,sql语句才加载。
延迟加载的解决方式是在配置文件中的<settings>下加如下两个配置:
<settings>
<!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
以上是关于mybatis级联查询,分步查询和延迟加载的主要内容,如果未能解决你的问题,请参考以下文章
[mybatis]映射文件_select_resultMap_关联查询_association分步查询&延迟加载
JavaLearn#(28)MyBatis高级:无级联查询级联查询(立即加载结果映射延迟加载)多表连接查询MyBatis注解MyBatis运行原理面试题