【Java】MyBatis应用(五)延迟加载
- 什么是延迟加载
- 在config.xml中开启延迟加载
延迟加载也叫懒加载、懒性加载,使用延迟加载可以提高程序的运行效率,针对于数据持久层的操作,在某些特定的情况下去访问特定的数据库,在其他情况下可以不访问某些表,从一定程序减少了Java应用与数据库的交互次数,
查询学生和班级的时候,学生和班级是两张不同的表,如果当前的需求只需要获取学生的信息,那么查询学生单表即可,如果需要通过学生获取对应的班级信息,则必须查询两张表。
不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的工作就是延迟加载
<settings>
<!-- 打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
StudentReposiotry接口
public Student findByILazy(long id);
StudentRepository.xml
<resultMap id="studentMapLazy" type="com.mybatistest.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.mybatistest.entity.Classes" select="com.mybatistest.repository.ClassesRepository.findByIdLazy" column="cid">
</association>
</resultMap>
<select id="findByILazy" parameterType="long" resultMap="studentMapLazy">
SELECT * FROM student where id = #{id}
</select>
ClassesRepository接口
public Classes findByIdLazy(long id);
ClassesRepository.xml
<select id="findByIdLazy" parameterType="long" resultType="com.mybatistest.entity.Classes">
SELECT * FROM classes WHERE id = #{id}
</select>

原文链接:【Java】MyBatis应用(五)延迟加载
姚姚的小站 版权所有,转载请注明出处。
还没有任何评论,你来说两句吧!