服务器之家

服务器之家 > 正文

java工程师进阶之MyBatis延迟加载的使用

时间:2022-01-04 13:08     来源/作者:DrLai

什么是延迟加载?

延迟加载也叫懒加载、惰性加载,使⽤延迟加载可以提⾼程序的运行效率,针对于数据持久层的操作, 在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从⼀定程度上减少了 Java 应⽤与数据库的交互次数。

查询学⽣和班级的时,学生和班级是两张不同的表,如果当前需求只需要获取学shengsheng的信息,那么查询学 ⽣单表即可,如果需要通过学⽣获取对应的班级信息,则必须查询两张表。 不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的⼯作就是延迟加载。

如何使用延迟加载?

1.在 config.xml 中开启延迟加载

?
1
2
3
4
5
6
<settings>
 <!-- 打印SQL-->
 <setting name="logImpl" value="STDOUT_LOGGING" />
 <!-- 开启延迟加载 -->
 <setting name="lazyLoadingEnabled" value="true"/>
</settings>

2.将多表关联查询拆分成多个单表查询

StudentRepository中

?
1
public Student findByIdLazy(long id);

StudentRepository.xml

?
1
2
3
4
5
6
7
8
9
10
<resultMap id="studentMapLazy" type="entity.Student">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <association property="classes" javaType="entity.Classes" select="repository.ClassesRepository.findByIdLazy" column="cld">
        </association>
    </resultMap>
    <select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
-- select s.id ,s.name,c.id as cid,c.name as cname from student s,classes c where s.id =1 and s.cld=c.id;
    select * from student where id=#{id};
    </select>

ClassesRepository

?
1
public Classes findByIdLazy(long id);
?
1
2
3
4
5
6
7
8
<resultMap id="classesMap" type="entity.Classes">
        <id column="cid" property="id"></id>
        <result column="cname" property="name"></result>
        <collection property="students" ofType="entity.Student">
            <id column="id" property="id"></id>
            <result column="name" property="name"></result>
        </collection>
    </resultMap>

以上就是java工程师进阶之MyBatis延迟加载的使用的详细内容,更多关于java之MyBatis延迟加载的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/DrLai/article/details/119753979

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部