Mybatis06_延迟加载
- 将原始的关联查询SQL改为单表查询,修改Map映射
StudentRepository.xml
<resultMap type="com.blu.entity.Student" id="studentLazyMap">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.blu.entity.Classes"
select="com.blu.repository.ClassesRepository.findByIdLazy" column="cid">
</association>
</resultMap>
<select id="findByIdLazy" parameterType="long" resultMap="studentLazyMap">
select * from student where id = #{id}
</select>
ClassesRepository.xml
<select id="findByIdLazy" parameterType="long" resultType="com.blu.entity.Classes">
select * from classes where id = #{id}
</select>
测试:
StudentRepository studentRepository = session.getMapper(StudentRepository.class);
Student student = studentRepository.findByIdLazy(1L);
System.out.println(student.getName());
==> Preparing: select * from student where id = ?
==> Parameters: 1(Long)
<== Columns: id, name, cid
<== Row: 1, 张三, 2
====> Preparing: select * from classes where id = ?
====> Parameters: 2(Long)
<==== Columns: id, name
<==== Row: 2, 2班
<==== Total: 1
<== Total: 1
张三
- 开启延迟加载
<settings>
<!-- 打印SQL -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延迟加载(默认关闭) -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
再次测试:
==> Preparing: select * from student where id = ?
==> Parameters: 1(Long)
<== Columns: id, name, cid
<== Row: 1, 张三, 2
<== Total: 1
张三