关联集合的获取(连接查询 & 分步查询),延迟加载
关联集合的获取和关联属性的获取过程很相似,仍然按照相同的顺序进行介绍。
public class College {
Integer id;
String name;
List<Student> students;
}
连接查询
public College getCollegeById(Integer id);
<select id="getCollegeById" resultMap="college">
select *
from college, student
where college.college_id = student.student_college
and college.college_id = #{id}
</select>
<resultMap id="college" type="com.test.entity.College">
<id column="college_id" property="id"></id>
<result column="college_name" property="name"></result>
<collection property="students" ofType="com.test.entity.Student">
<id property="id" column="student_id"></id>
<result property="name" column="student_name"></result>
</collection>
</resultMap>
注意,colection
的ofType
属性***一定不能省略,它用来指出集合中的元素的类型***
分步查询
<select id="getCollegeById" resultMap="college">
select *
from college
where college.college_id = #{id}
</select>
<resultMap id="student" type="com.test.entity.Student">
<id column="student_id" property="id"></id>
<result column="student_name" property="name"></result>
<association property="college" select="com.test.dao.ICollegeDao.getCollegeByIdWithoutDependence" column="id=student_college">
<id property="id" column="college_id"></id>
<result property="name" column="college_name"></result>
</association>
</resultMap>
双向关联分步查询的问题:无限递归,导致堆溢出
当双向关联都使用分步查询时,创建A需要创建B,创建B需要创建A,就这样一致递归下去,导致堆内存溢出。
解决方法,可以使用连接查询,这样创建A时不需要调用B的方法。
另一个解决方法就是需要与之关联的对象提供一个没有依赖的方法,这样就不会产生相互依赖。
小结
不要忘记ofType
属性
使用association
标签时,不用指定属性;但是使用collection
时,必须指定bean的类型。
延迟加载问题
- 通过全局配置
- 通过
fetchType
属性配置