需求中一对多实现的三种方式
其中两种分别使用association,collection
准备库表字段
学生表/老师表(一个老师对应多个学生)
内部类
一、常见方法
分别查出教师和学生信息,后add整合
@RequestMapping("/aaaa")
public TeacherVo aaa(){
TeacherVo teacherVo=aaaMapper.getTeacherVo(1);
List<TeacherVo.Student> students= aaaMapper.getStudentVo(teacherVo.getTeacherId());
teacherVo.setStudents(students);
return teacherAndStudent;
}
二、使用collection
使用关联查询,利用resultMap中的<collection>标签实现对字段的映射
TeacherVo teacherAndStudent = modelSuperviseRulesService.getTeacherAndStudent(1);
<resultMap id="studentMap" type="com.sz.entity.vo.TeacherVo">
<collection property="students" javaType="ArrayList" ofType="com.sz.entity.vo.TeacherVo$Student" column="teacherId" select="getStudentVo"/>
</resultMap>
<select id="getTeacherAndStudent" resultMap="studentMap">
SELECT
t1.id teacherId,
t1.teacherName
FROM
`a_teacher` t1
where t1.id=#{teacherId}
</select>
<select id="getStudentVo" resultType="com.sz.entity.vo.TeacherVo$Student">
SELECT
studentName,
id
FROM
`a_student`
where t_id=#{teacherId}
</select>
三、使用association
使用关联查询,利用resultMap中的<association>标签实现对字段的映射
TeacherVo teacherAndStudent = modelSuperviseRulesService.getTeacherAndStudent(1);
<resultMap id="studentMap" type="com.sz.entity.vo.TeacherVo">
<result column="id" property="teacherId" />
<result column="teacherName" property="teacherName" />
<association property="students" resultMap="KeyStudentsMap" />
</resultMap>
<resultMap id="KeyStudentsMap" type="com.sz.entity.vo.TeacherVo$Student">
<result column="studentName" property="studentName" />
</resultMap>
<select id="getTeacherAndStudent" resultMap="studentMap">
SELECT
t1.id teacherId,
t1.teacherName ,
t2.studentName studentName
FROM
`a_teacher` t1
left join a_student t2 on t1.id=t2.t_id
where t1.id=#{teacherId}
</select>