下面有两个实体类:部门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语句,因此提升了效率