- 不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的工作就是延迟加载。
(1)在config.xml中开启延迟加载
<settings>
<!-- 打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
(2)StudentRepository
Student findByIdLazy(long id);
(3)StudentRepository.xml
<!-- 延迟加载 -->
<resultMap id="lazy" type="com.lin.entity.Student">
<id property="id" column="id"></id>
<result column="studentName" property="studentName"></result>
<association property="classes" javaType="com.lin.entity.Classes" select="com.lin.repository.ClassesRepository.findByIdLazy" column="classID"></association>
</resultMap>
<select id="findByIdLazy" resultMap="lazy" parameterType="java.lang.Long">
select * from student where id=${id}
</select>
- select :查找其他表的方法
- colum:依照的参数
(4)ClassesRepository
Classes findByIdLazy(long id);
(5)ClassesRepository.xml
<!-- 延迟加载 -->
<select id="findByIdLazy" resultType="com.lin.entity.Classes" parameterType="java.lang.Long">
select * from classes where id=#{id}
</select>
(6)使用
在这种情况下会执行一次sql语句
StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
Student student = studentRepository.findByIdLazy(3);
System.out.println(student.getStudentName());
在这种情况下会执行两次
System.out.println(student.getClasses());