好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

什么是延迟加载?

延迟加载也叫懒加载、惰性加载,使⽤延迟加载可以提⾼程序的运行效率,针对于数据持久层的操作, 在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从⼀定程度上减少了 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

查看更多关于java工程师进阶之MyBatis延迟加载的使用的详细内容...

  阅读:12次