Mybatis使用association时的执行效率(N+1)问题

  下面有两个实体类:部门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>
SELECT * FROM employee LEFT JOIN department ON employee.deptid=department.id

这样只需要执行一条sql语句,因此提升了效率

转载于:https://www.cnblogs.com/uvchan/p/10573117.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值