mybatis使用associaton进行分步查询

Employee

public class Employee {
	
	private Integer id;
	private String lastName;
	private String email;
	private String gender;
	private Department dept;
    // 省略setter、getter、toString方法
}

Department

public class Department {
	
	private Integer id;
	private String departmentName;
	private List<Employee> emps;
}

再来看EmployeeMapper.xml中的相关语句

	<!-- 使用association进行分步查询:
		1、先按照员工id查询员工信息
		2、根据查询员工信息中的d_id值去部门表查出部门信息
		3、部门设置到员工中;
	 -->
	 
	 <!--  id  last_name  email   gender    d_id   -->
	 <resultMap type="com.mybatis.bean.Employee" id="MyEmpByStep">
	 	<id column="id" property="id"/>
	 	<result column="last_name" property="lastName"/>
	 	<result column="email" property="email"/>
	 	<result column="gender" property="gender"/>
	 	<!-- association定义关联对象的封装规则
	 		select:表明当前属性是调用select指定的方法查出的结果
	 		column:指定将哪一列的值传给这个方法
	 		流程:使用select指定的方法(传入column指定的这列参数的值)查出对象,并封装给property指定的属性
	 	 -->
 		<association property="dept" 
	 		select="com.mybatis.dao.DepartmentMapper.getDeptById"
	 		column="d_id">
 		</association>
	 </resultMap>
	 <!--  public Employee getEmpByIdStep(Integer id);-->
	 <select id="getEmpByIdStep" resultMap="MyEmpByStep">
	 	select * from tbl_employee where id=#{id}
	 </select>

DepartmentMapper.xml中的相关语句

<!--public Department getDeptById(Integer id);  -->
	<select id="getDeptById" resultType="com.mybatis.bean.Department">
		select id,dept_name departmentName from tbl_dept where id=#{id}
	</select>

通过association实现了分步查询,在一定程度上简化了sql语句,另外association还指支持延迟加载(懒加载),目前的情况是当我们执行了getEmpByIdStep语句,也一定执行DepartmentMapper.xml中的getDeptById语句,但如果并不需要部门表中的信息呢?

如:

			Employee employee = mapper.getEmpByIdStep(3);
			System.out.println(employee);

查询id为3的员工的信息,此时我们并不需要部门表的信息,那可以用懒加载的方式进行。

需要在mybatis全局配置文件mybatis-config.xml中开启

	<settings>
		<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>

对于这两个属性,我们来看一下mybatis官方文档中的介绍

当这样设置后,当我们再次运行

	Employee employee = mapper.getEmpByIdStep(3);
			System.out.println(employee);

通过控制台的打印sql语句可以发现,并未执行查询部门的sql语句


Employee employee = mapper.getEmpByIdStep(3);
System.out.println(employee.getDept());

当这样调用时,就会调用查询部门的语句,实现了按需加载。

posted @ 2019-07-11 22:22  HeliusKing  阅读(3893)  评论(0编辑  收藏  举报