ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Mybatis学习笔记:延迟加载

2026/9/23 6:18:22 拓冰建站 浏览量
Mybatis学习笔记:延迟加载

本文是自己的学习笔记,主要参考以下资料

- 马士兵教育

  • 1、延迟加载
  • 2、开启延迟加载
    • 2.1、配置信息
    • 2.2、查询语法
      • 2.2.1、前置条件
      • 2.2.2、xml语法
      • 2.2.3、总结

1、延迟加载

延迟加载是用于优化一对多或者多对多的查询。

比如员工表和部门表,员工表left join部门表,一条SQL查出所有数据。

但有时候部门表的使用频率很低,这时候我们就可以使用延迟加载,先查出员工数据,等需要用到部门数据的时候再执行剩下的查询。

2、开启延迟加载

2.1、配置信息

延迟加载与这两个属性有关。

  • lazyLoadingEnabled: ture|false,true开启延迟加载。与aggressiveLoadingEnabled是相反的属性。
  • aggressiveLoadingEnabled: ture|false,true开启全加载。与lazyLoadingEnabled是相反的属性。

mybatis.xml中,configuration标签下这样设置可开启全局延迟加载。

<configuration><settings><setting name="lazyLoadingEnabled" value="true"/><setting name="aggressiveLoadingEnabled" value="false"/></settings>
</configuration>

2.2、查询语法

2.2.1、前置条件

现有两个POJO,Emp--员工,Dept--部门。两者的类如下,数据库字段同名。

public class Dept {private Integer deptid;private String dname;
}
public class Emp {private Integer id;private String name;private Integer age;private Dept dept;
}

2.2.2、xml语法

现在是查员工表,left join出部门表。部门数据延迟加载。

我们不能直接使用left join关联数据,因为数据库语句一执行就会查出所有数据,不会收到lazyLoadingEnabled的影响。

我们需要将原来的left join拆成两个查询,然后在配置中关联。这样查询过程就受mybatis的控制。

需要拆成两个查询一个是查询员工表,另一个是查询部门表。

<select id="queryDeptById">select * from t_dept where deptid = #{deptid}
</select><select id="queryEmp" resultMap="baseMap1">select * from t_emp
</select>

之后定义返回值,也是在这里定义关联关系。

<resultMap id="baseMap" type="emp"><id column="id" property="id"/><result column="name" property="name"/><result column="age" property="age"/><association property="dept" javaType="Dept" column="deptId" select="queryDeptById"><id column="deptid" property="deptid"/><result column="dname" property="dname"/></association>
</resultMap>

2.2.3、总结


<resultMap id="baseMap" type="emp"><id column="id" property="id"/><result column="name" property="name"/><result column="age" property="age"/><association property="dept" javaType="Dept" column="deptId" select="queryDeptById"><id column="deptid" property="deptid"/><result column="dname" property="dname"/></association>
</resultMap><select id="queryDeptById">select * from t_dept where deptid = #{deptid}
</select><select id="queryEmp" resultMap="baseMap1">select * from t_emp
</select>