当前位置: 首页> 游戏> 游戏 > MyBatis中复杂查询(一对多和多对一)

MyBatis中复杂查询(一对多和多对一)

时间:2025/7/10 18:08:43来源:https://blog.csdn.net/qq_44858608/article/details/140208220 浏览次数:0次

一,介绍

        在MyBatis中处理一对多(1)和多对一(N:1)关系是常见的需求,尤其是在操作数据库中存在关联表时。这些关系的管理能让数据查询更加直观和灵活。下面分别介绍如何在MyBatis中配置和查询这两种类型的关系。

二,一对多(1)关系

        一对多关系指的是一个记录在一个表中可以关联多个记录在另一个表中。例如,一个课程可以有多个学生。通常我们需要用外键关联学生与课程并一同返回结果。

 2.1映射配置

        首先在MyBatis的映射文件中配置这种关系。假设我们有两个实体类:Course和 Student,其中 Course可以有多个 Student。

2.2 Course类

public class Course {private int id;private String name;private List<Student> students; // 课程对应的学生列表// getters 和 setters
}

2.3 Student类:

public class Student {private int id;private String name;private int courseId; // 外键// getters 和 setters
}

2.4 Mapper文件

<select id="selectCourse" resultMap="CourseResultMap">SELECT * FROM CourseLEFT JOIN Student ON Course.id = Student.course_idWHERE Course.id = #{id}
</select><resultMap id="CourseResultMap" type="Course"><id property="id" column="id" /><result property="name" column="name" /><collection property="students" ofType="Student"resultMap="StudentResultMap"/>
</resultMap><resultMap id="StudentResultMap" type="Student"><id property="id" column="id" /><result property="name" column="name" /><result property="courseId" column="course_id" />
</resultMap>

二,多对一(N:1)关系

        多对一关系指的是多个记录在一个表中可以关联到另一个表中的单个记录。例如,多个学生可以属于同一个课程。

 2.1 映射配置(添加字段名与类属性名不一致的情况)

        通过映射文件中的配置来指定数据库字段名和类属性名之间的对应关系。我在多对一(N:1)关系的例子中加入字段名和参数名不一样的情况。比如,在数据库中字段名为id而在类中的对应字段名为courseId。

2.2 Student类:

public class Student {private int id;private String name;private int courseId; // 对应数据库中的 course_id 字段private Course course; // 关联的课程对象// getters 和 setters
}

2.3 Course类

public class Course {private int courseId; // 注意,这里使用了 courseId 而不是 idprivate String name;// getters 和 setters
}

2.4 Mapper文件配置

<!-- 结果映射定义,处理字段名和属性名不一致的情况 -->
<resultMap id="CourseResultMap" type="Course"><id property="courseId" column="id" />  <!-- 映射数据库的 id 字段到类的 courseId 属性 --><result property="name" column="name" />
</resultMap><resultMap id="StudentResultMap" type="Student"><id property="id" column="id" /><result property="name" column="name" /><result property="courseId" column="course_id" />  <!-- 映射数据库的 course_id 字段到类的 courseId 属性 --><association property="course" javaType="Course"resultMap="CourseResultMap" />
</resultMap><!-- 查询学生及其课程信息,处理字段名映射 -->
<select id="selectStudent" resultMap="StudentResultMap">SELECT Student.id, Student.name, Student.course_id,Course.id, Course.nameFROM StudentJOIN Course ON Student.course_id = Course.idWHERE Student.id = #{id}
</select>

关键字:MyBatis中复杂查询(一对多和多对一)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: