延迟加载顾名思义,就是加载的时间推迟了,推迟加载的是什么呢,就是目前用不到的数据,延迟加载可以用在分布查询上,就是先查询一个表,再根据这个表里面的信息去查询另一个表的信息,分步查询将两个查询链接起来取得的信息构成返回的数据集,延迟加载就是如果你通过这个这个接口去调用这个分步查询得到的结果,如果你只用的到其中第一步就可以查询出来的信息,那么就不会去执行第二步查询,以此来达到提高系统性能的效果,当你需要用到第二个查询才能得到的数据时,那么这时才会去执行分步查询的第二步。
示例
Entity
@Data
public class Student {
private Integer id;
private String name;
private Integer tid;
@TableField(exist = false)
private Teacher teacher;
}
@Data
@TableName("teacher")
public class Teacher {
@TableId
private Integer tid;
private String name;
@TableField(exist = false)
private List<Student> students;
}
Mapper
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
/*分布查询*/
//查询Student消息
Student getStudentByStep01(@Param("id") Integer id);
}
@Mapper
public interface TeacherMapper extends BaseMapper<Teacher> {
//通过tid查询Teacher
Teacher getTeacherByTid(@Param("tid") Integer tid);
}
mapper.xml
<!--解决一对多映射关系03 分步查询-->
<!--Student getStudentByStep01(@Param("id") Integer id);-->
<select id="getStudentByStep01" resultMap="getStudentByStep02">
select *
from student
where id = #{id};
</select>
<resultMap id="getStudentByStep02" type="student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="tid" column="tid"/>
<!--property属性名 column查询语句的参数-->
<association property="teacher" column="tid"
select="com.lzw.boot.mapper.TeacherMapper.getTeacherByTid"/>
</resultMap>
<!--延迟加载策略 -->
<!--Teacher getTeacherByTid(@Param("tid") Integer tid);-->
<select id="getTeacherByTid" resultType="teacher" parameterType="integer">
select *
from teacher
where tid = #{tid};
</select>
application.yml
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.lzw.boot.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
lazy-loading-enabled: true #延迟加载全局开关
# aggressive-lazy-loading 开启时,任何方法的调用都会珈载该对象的所有属性。
# 否则,每个属性会按需加载 3.4.1之后默认关闭,之前是默认开启
aggressive-lazy-loading: false
map-underscore-to-camel-case: true #映射对象class和数据 进行驼峰命名匹配
测试
1、如果直接查询结果集,而不用,那么只执行分步查询的第一步

2、如果查询的结果你只用到了第一步就可以得到的数据,那么就不会执行第二步查询

3、如果需要用到第二步查询才能得到的结果,那么才会执行第二部

以上就是延迟查询的效果以及应用,分步查询+延迟加载,在一定情况下可以为我们提升速度,他可以完全避免浪费没有必要的资源,有错误敬请指正!
延迟加载是一种优化系统性能的技术,主要应用于分布查询中。当不需要立即使用所有数据时,它推迟加载暂时用不到的部分。例如,在学生和教师的例子中,先查询学生信息,只有在需要教师详情时才执行第二步查询。这种方式可以避免不必要的资源浪费,提高查询效率。在实际应用中,可以通过配置MyBatis-Plus的懒加载和侵略性懒加载选项来控制延迟加载的行为。
1526

被折叠的 条评论
为什么被折叠?



