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());

當這樣調用時,就會調用查詢部門的語句,實現了按需加載。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM