下面有兩個實體類:部門Department和職員Employee(忽略其構造方法及getter,setter方法)
private String id;//主鍵 private String deptName;//部門名稱 private String id;//主鍵 private String empName;//用戶姓名 private Department dept;//用戶部門
當在association中進行查詢職員時Mapper文件如下
<mapper namespace="com.chan.dao.EmployeeDao"> <resultMap type="com.chan.beans.Employee" id="EmployeeMap"> <association property="id" column="DeptId" javaType="com.chan.beans.Department" select="getDepartment"> </association> </resultMap> <select id="getDepartment" resultType="com.chan.beans.Department"> SELECT * FROM department WHERE id=#{id} </select> <select id="getEmployee" resultMap="EmployeeMap"> SELECT * FROM employee </select> </mapper>
mybatis會先查詢出所有符合條件的雇員,然后根據查詢到的第一個雇員的deptid查詢出該雇員所在的部門信息. 在查詢之后的雇員所在部門信息時,mybatis會把雇員的部門id與已經緩存的部門信息進行對比,如果緩存中沒有該部門的部門id,則會執行新的sql語句進行查詢. 因此,查詢語句的執行次數為:
select distinct count(deptId)+1 from department;
當使用表關聯進行查詢然后在association中進行映射時Mapper文件如下:
<mapper namespace="com.chan.dao.EmployeeDao"> <resultMap type="com.chan.beans.Employee" id="EmployeeMap"> <ssociation property="id" column="DeptId" javaType="com.chan.beans.Department"> <id property="id" column="deptid"/> <result property="deptName" column="deptName"/> </association> </resultMap> <select id="getEmployee" resultMap="EmployeeMap"> SELECT e.*,d.id as deptid,d.name as deptname FROM employee e LEFT JOIN department d ON e.deptid=d.id </select> </mapper>
這樣只需要執行一條sql語句,因此提升了效率