多对多关联查询
一个学生可以选修多门课程,一门课程也可以被多个学生选修。
假设有三个实体类Student、Course和StudentCourse,其中Student和Course是主实体类,StudentCourse是关联表。
public class Student {
private Integer id;
private String name;
private List<Course> courses; // 多对多关联,使用List集合保存选修的课程对象
// Getters and setters (省略)...
}
public class Course {
private Integer id;
private String name;
private List<Student> students; // 多对多关联,使用List集合保存选修该课程的学生对象
// Getters and setters (省略)...
}
public class StudentCourse {
private Integer studentId;
private Integer courseId;
// Getters and setters (省略)...
}
Mapper接口StudentMapper中,定义多对多关联查询的方法:
javaCopy code
public interface StudentMapper {
Student getStudentWithCoursesById(Integer id);
}
在MyBatis的映射文件StudentMapper.xml中,使用****标签来进行多对多关联查询:
<!-- 定义Course的结果映射 -->
<resultMap id="courseMap" type="Course">
<id property="id" column="course_id"/>
<result property="name" column="course_name"/>
<!-- 其他Course属性的映射... -->
</resultMap>
<!-- 定义Student的结果映射,包含对Course对象的集合映射 -->
<resultMap id="studentMap" type="Student">
<id property="id" column="student_id"/>
<result property="name" column="student_name"/>
<!-- 其他Student属性的映射... -->
<collection property="courses" ofType="Course" resultMap="courseMap"/>
</resultMap>
<!-- 定义查询语句,通过resultMap属性引用studentMap结果映射 -->
<select id="getStudentWithCoursesById" resultMap="studentMap">
SELECT s.id as student_id, s.name as student_name,
c.id as course_id, c.name as course_name
FROM students s
LEFT JOIN student_course sc ON s.id = sc.student_id
LEFT JOIN courses c ON sc.course_id = c.id
WHERE s.id = #{id}
</select>
- 定义了Course类的结果映射courseMap
- 定义了Student类的结果映射studentMap
- 在studentMap结果映射中,使用标签指定了属性courses与结果映射courseMap的嵌套关联
- 通过ofType属性指定集合中元素的类型为Course
<collection property="propertyName" ofType="elementType" resultMap="resultMapId"/>
常用属性:
- property:指定Java对象中的属性名,用于表示关联对象的集合属性。
- ofType:指定集合中元素的类型,即关联对象的类型。ofType属性在多对多关联中使用
- resultMap:指定关联对象的结果映射id,即关联对象的标签的id。