这一篇主要介绍一对多关系的实现,以及对关系映射的总结。
在上一篇的基础上,引入班级表 t_grade(id,gradeName)
里面的一对多的关系:一个班级对应多个学生。
一对一的关系:一个学生对应一个班级,一个地址。
一对多关系实现
既然一个班级有多个学生,就在班级实体里注入List<Student>
班级实体属性: id,gradeName,students(List<Student>)
<mapper namespace="com.java.mappers.GradeMapper">
<resultMap type="Grade" id="GradeResult">
<id property="id" column="id"/>
<result property="gradeName" column="gradeName"/>
<collection property="students" column="id" select="com.java.mappers.StudentMapper.findByGradeId"></collection>
</resultMap>
<select id="findById" parameterType="Integer" resultMap="GradeResult">
select * from t_grade where id=#{id}
</select>
</mapper>
在班级映射里,collection 通过传递进去的主键id,调用StudentMapper里的findByGradeId方法获得Student对象的集合,注入给属性students.
从而实现一对多的实现。
而StudentMapper里:
<mapper namespace="com.java.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="grade" column="gradeId" select="com.java.mappers.GradeMapper.findById"></association>
<association property="address" column="addressId" select="com.java.mappers.AddressMapper.findById"></association>
</resultMap>
<select id="findById" parameterType="Integer" resultMap="StudentResult">
select * from t_student where id=#{id}
</select>
<select id="findByGradeId" parameterType="Integer" resultMap="StudentResult">
select * from t_student where gradeId=#{gradeId}
</select>
<select id="findByAddressId" parameterType="Integer" resultMap="StudentResult">
select * from t_student where addressId=#{addressId}
</select>
</mapper>
获得的Student也是有地址信息的。
关系映射的总结
- 一对一关系实现:虽然实现方式有多种,不过以后开发还是用最后那种。缺什么就向谁要东西。理解association的过程:根据column里面的字段名,执行方法,获取相应对象,给property里的值。
- 一对多关系的实现:理解collection的过程:根据column里面的字段名,执行获取对象的方法,获得多个对象,以集合形式,给property里的集合属性。