第一种方式:嵌套结果集方式
第二种方式:分步查询方式,通过association定义联合的对象
第三种方式:使用association分步查询
场景:查出employee同时查出部门,employee–>department
javaBean和表
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;}
//对应表:tbl_employee->id,last_name,gender,email,d_id
public class Department {
private Integer id;
private String name;}
// 对应表:tbl_dept->id,dept_name
第一种方式:嵌套结果集方式
<resultMap id="myEmpDiff" type="com.stayreal.mybatis.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<result column="did" property="dept.id"/>
<result column="dept_name" property="dept.name"/>
</resultMap>
<!--public Employee getEmpAndDept(Integer id);-->
<select id="getEmpAndDept" resultMap="myEmpDiff">
select e.id,e.last_name,e.email,e.gender,e.d_id,
d.id did,d.dept_name from tbl_employee e,tbl_dept d
where e.d_id = d.id and e.id=#{id}
</select>
//Junit:
Employee employee = mapper.getEmpAndDept(1);
System.out.println(employee.toString());
System.out.println(employee.getDept());
//Employee{id=1, lastName='Jerry', email='Jerry@qq.com', gender='1'}
//Department{id=2, name='ceshi'}
第二种方式:通过association定义联合的对象
<resultMap id="myEmpDiff2" type="com.stayreal.mybatis.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<!--association 可以指定联合的对象
property="dept":指定哪个属性是联合的对象
javaType:指定类型
-->
<association property="dept" javaType="com.stayreal.mybatis.Department">
<id column="did" property="id"/>
<result column="dept_name" property="name"/>
</association>
</resultMap>
第三种方式:使用association分步查询
<!--
1. 先查员工信息
2. 再查部门表
3. 部门设置到员工中
使用select指定的方法,查出对象,传入column定义的参数
-->
<resultMap id="myEmpByStep" type="com.stayreal.mybatis.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
<association property="dept" select="com.stayreal.mybatis.DepartmentMapper.getDepartmentById"
column="d_id">
</association>
</resultMap>
<!--public Employee getEmpByIdStep(Integer id);-->
<select id="getEmpByIdStep" resultMap="myEmpByStep">
select * from tbl_employee where id=#{id}
</select>
分步查询支持延迟加载:
employee->dept 我们每次查询employee对象的时候,都将一起查出,
部门信息在我们使用的时候再去查询
分步查询的基础之上加上两个配置
支持延迟加载,可以在全局配置mybatis-config.xml中增加
<!-- 显示的指定每个需要更改的值 即使是默认的,从而防止版本更新带来的问题 延迟加载 懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>