文章目录
关联属性的封装(连接查询 & 分步查询),延迟加载
在项目中,不可避免的存在着类与类之间的关联,在数据库的表中,这样的关联使用关联属性的主键表示;但在对象中,被关联的属性一般是以对象的形式存在。
举个例子:
学生Student
和学院College
是多对一的关系,在这里,学生类可以有一个字段,用来存储他/她所在的学院。
public class Student {
Integer id;
String name;
College college;
}
使用连接查询
使用连接查询获得college,并且封装到student对象中
public Student getStudentById(Integer id);
<select id="getStudentById" resultMap="student">
select *
from student, college
where studet.stuent_college = college.college_id
and student_id = #{id}
</select>
有了查询的结果,显然Mybatis不能自动封装,需要根据我们配置的reslutMap
进行封装。
方式一:嵌套封装
<resultMap id="student" type="com.test.entity.Student">
<id column="student_id" property="id"></id>
<result column="student_name" property="name"></result>
<!-- 封装college,经过连接查询,已经将对应的学院信息查询出来了 -->
<asso