工作中数据表之间关联的情况太常见了,本文针对工作中常用的一对多/一对一;多对一进行说明;
1、一对多/一对一
比如:
1、多个学生对应一个老师;
2、一个学生对应一个老师(家教老师/私人一对一)
<resultMap id="studentResult" type="Student">
<!--association关联属性 property属性名 javaType属性类型 column是在多的一方的表中维护的一的一方的列名;这里就是学生表中关联了教师表的id-->tid -->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
//根据关联的id查询教师信息 (这里也可以使用resultType 注意查询属性为空的情况,需要开启配置驼峰转大写)
<select id="getTeacher" resultMap="xxxxx.mapper.Teacher.TeacherResult">
select * from teacher where id = #{id}
</select>
2、多对一
比如:一个老师对应多个学生
<resultMap id="TeacherResult" type="Teacher">
<!--column是一对多的外键 , 写的是一的主键的列名 -->
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
</resultMap>
//(这里也可以使用resultType 注意查询属性为空的情况,需要开启配置驼峰转大写)
<select id="getStudentByTeacherId" resultMap="xxxxx.mapper.StudentMapper.studentResult">
select * from student where tid = #{id}
</select>
说明:以上的一对一/多;多对一 都可以使用联查的方式进行实现,然后在中使用属性映射的方式实现,没问题,看个人喜好。