温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中MyBatis延迟加载怎么用

发布时间:2021-09-15 12:55:13 来源:亿速云 阅读:101 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关java中MyBatis延迟加载怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

什么是延迟加载?

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

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

如何使用延迟加载?

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

<settings>
 <!-- 打印SQL-->
 <setting name="logImpl" value="STDOUT_LOGGING" />
 <!-- 开启延迟加载 -->
 <setting name="lazyLoadingEnabled" value="true"/>
</settings>

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

StudentRepository中

 public Student findByIdLazy(long id);

StudentRepository.xml

<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

public Classes findByIdLazy(long id);
<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延迟加载怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI