服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - MyBatis深入解读懒加载的实现

MyBatis深入解读懒加载的实现

2022-11-25 14:47羡羡ˇ Java教程

顾名思义,懒加载就是因为偷懒了,懒得加载了,只有使用的时候才进行加载。其实,懒加载也加延迟加载,主要以应用与Mybatis的关联查询,按照设置的延迟规则,推迟对延迟对关联对象的select查询

懒加载 ,也称为嵌套查询

       需要查询关联信息时,使用 Mybatis 懒加载特性可有效的减少数据库压力, 首次查询只查询主表信息,关联表的信息在用户获取时再加载。        

       Mybatis 一对一关联的 association 和一对多的 collection 可以实现懒加载。懒加载时要 使用resultMap,不能使用 resultType 。

这里我们以员工表和部门表为例 

MyBatis深入解读懒加载的实现

通过deptId 与 部门表 id 关联

 我们这里首先需要开启一个设置

?
1
2
3
4
<settings>
    <!--指定哪些方法去触发延迟加载,hashCode,equals,clone,toString-->
    <setting name="lazyLoadTriggerMethods" value=""/>
</settings>

懒加载功能是默认开启的, 但这里我们也需要设置这个属性, 不设置则不会触发延迟加载功能

?
1
Employee selectOneEmployee(int id);

我们以查询单个员工为例 , resultMap 与sql 如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--定义resultMap-->
<resultMap id="employeeMap1" type="Employee">
   <id column="id" property="id"/>
   <result property="name" column="name"/>
   <result property="age" column="age"/>
   <!--fetchType为查询的类型,这里选择lazy  select为嵌套查询-->
   <association property="dept" javaType="Dept" fetchType="lazy"
         select="selectDept" column="deptId">
   <result column="name" property="name"/>
   </association>
</resultMap>
<select id="selectOneEmployee" resultMap="employeeMap1">
   select id,name,age,deptId from employee where id=#{id}
</select>
<!--通过上一级sql提供的deptId查询-->
<select id="selectDept" resultType="Dept">
   select name from dept where id=#{deptId}
</select>

此处一对一 ,我们使用<association>

java测试 : 

?
1
2
3
4
5
6
7
8
public static void main(String[] args) {
   SqlSession sqlSession= MybatisUtil.getSqlSession();
   EmployeeDao mapper=sqlSession.getMapper(EmployeeDao.class);
   Employee employee = mapper.selectOneEmployee(3);
   System.out.println(employee);
   System.out.println(employee.getDept());
   sqlSession.commit();  //提交事务
   sqlSession.close();   //关闭

查询结果 :

MyBatis深入解读懒加载的实现

通过结果可以看到 , 当我们第一次输出这个 employee 对象时, 部门是没有被查询的 , 而当我们需要使用到部门的信息时, 才会去触发这个查询 

查询部门 resultMap 与 sql如下: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<resultMap id="deptMap1" type="Dept">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <!--collection为一对多 , 这里一个部门包含多个员工-->
    <collection property="list" javaType="List" ofType="Employee"
          select="selectEmployee" fetchType="lazy" column="id">
    <result property="name" column="name"/>
    </collection>
</resultMap>
<select id="selectOneDept" resultMap="deptMap1">
    SELECT id,name FROM dept where id=#{id}
</select>
<select id="selectEmployee" resultType="Employee">
    select name from employee where deptId=#{id}
</select>

一对多,我们使用<collection>

懒加载就介绍到这里,感谢阅读

到此这篇关于MyBatis深入解读懒加载的实现的文章就介绍到这了,更多相关MyBatis懒加载内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/xx12321q/article/details/123848565

延伸 · 阅读

精彩推荐