首页 > 代码库 > (6)MyBatis之多对多关联

(6)MyBatis之多对多关联

  • 引言
  • MyBatis之多对多
    • 1 创建我们的数据库
    • 2 创建Student持久化类
    • 3 创建Course持久化类
    • 4 创建CS持久化类用于查询某学生某课程的成绩
    • 5 根据需求编写映射文件
      • 51 Student的映射文件
      • 52 Course映射文件
      • 53 CS映射文件
    • 6 编写SQL相应的语句
      • 61 查询选修某课程的所有学生一个Course对象里面有Student数组
      • 62 查询某学生查询的课程信息一个Student对象里面有Course数组
      • 63 查询某学生某课程的成绩信息
    • 7 编写测试类
      • 71 查询选修某课程的所有学生一个Course对象里面有Student数组
      • 72 运行结果
      • 73 查询某学生查询的课程信息一个Student对象里面有Course数组
      • 74 运行结果
      • 75 查询某学生某课程的成绩信息
      • 76 运行结果
  • 代码下载
      • 本博客的代码下载地址为MyBatis之多对多

1.引言

      在本篇博客中主要介绍:

  • MyBatis如何建立多对多的关联,在多对多关系中:映射文件应该如何编写,持久化类应该如何写?

2. MyBatis之多对多

      在涉及到代码之前,我们先说一下数据库中的表结构:

  • 数据库中有三张表:student表(学生表),course表(课程表),course_student表(学生课程表)
student表:sid学号,sname学生名,hobit爱好
course表:cid课程号,name课程名称,dec课程描述
course_student表,sc_id主键,sid外键,cid外键,grade分数
  • 我们一共有三个需求:

    第一个:查询 选修某课程的学生信息
    第二个:查询 某学生选修的课程信息
    第三个:查询 某学生某课程 的学习成绩
    

2.1 创建我们的数据库

DROP DATABASE IF EXISTS school;
CREATE DATABASE IF NOT EXISTS school;
USE school;
CREATE TABLE `student`(
`sid` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`sname` VARCHAR(32) ,
`hobit` VARCHAR(20)
);
CREATE TABLE `course`(
`cid` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR(32) ,
`dec` VARCHAR(20)
);
CREATE TABLE `course_student`(
sc_id INT AUTO_INCREMENT PRIMARY KEY,
sid INT ,
cid INT,
grade INT
);
ALTER TABLE course_student ADD CONSTRAINT  FOREIGN KEY(sid) REFERENCES student(sid);
ALTER TABLE course_student ADD CONSTRAINT  FOREIGN KEY(cid) REFERENCES course(cid);
INSERT INTO `student` (`sid`,`sname`,`hobit`)
VALUES(1,"aaa","喜欢玩游戏");
INSERT INTO `student` (`sid`,`sname`,`hobit`)
VALUES(2,"bbb","喜欢学习");
INSERT INTO `student` (`sid`,`sname`,`hobit`)
VALUES(3,"ccc","喜欢打篮球");
INSERT INTO `course` (`cid`,`name`,`dec`)
VALUES(1,"math","数学课程");
INSERT INTO `course` (`cid`,`name`,`dec`)
VALUES(2,"english","英语课程");
INSERT INTO `course` (`cid`,`name`,`dec`)
VALUES(3,"chinese","语文课程");
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(1,1,82);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(1,2,77);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(1,3,65);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(2,1,92);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(2,2,100);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(2,3,72);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(3,1,65);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(3,2,58);
INSERT INTO `course_student` (`sid`,`cid`,`grade`)
VALUES(3,3,57);

2.2 创建Student持久化类

package com;

import java.util.List;

public class Student {
    private Integer sid;
    private String sname;
    private String hobit;
    //创建多对多关系
    private List<Course> courses;
    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname == null ? null : sname.trim();
    }
    public String getHobit() {
        return hobit;
    }
    public void setHobit(String hobit) {
        this.hobit = hobit == null ? null : hobit.trim();
    }
    public List<Course> getCourses() {
        return courses;
    }
    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }
}

2.3 创建Course持久化类

package com;

import java.util.List;

public class Course {
    private Integer cid;
    private String name;
    private String dec;
    //创建多对多关系
    private List<Student> students;
    public Integer getCid() {
        return cid;
    }
    public void setCid(Integer cid) {
        this.cid = cid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
    public String getDec() {
        return dec;
    }
    public void setDec(String dec) {
        this.dec = dec == null ? null : dec.trim();
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

2.4 创建CS持久化类(用于查询某学生某课程的成绩)

package com;
public class CS {
    private Integer sc_id;
    //某学生
    private Student student;
    //某课程
    private Course course;
    //该课程的成绩
    private String grade;
    public Integer getSc_id() {
        return sc_id;
    }
    public void setSc_id(Integer sc_id) {
        this.sc_id = sc_id;
    }
    public Student getStudent() {
        return student;
    }
    public void setStudent(Student student) {
        this.student = student;
    }
    public Course getCourse() {
        return course;
    }
    public void setCourse(Course course) {
        this.course = course;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }
}

2.5 根据需求编写映射文件

2.5.1 Student的映射文件

<resultMap id="StudentMap" type="com.Student" >
    <id column="sid" property="sid" jdbcType="INTEGER" />
    <result column="sname" property="sname" jdbcType="VARCHAR" />
    <result column="hobit" property="hobit" jdbcType="VARCHAR" />
    <collection property="courses" ofType="com.Course">
      <id column="cid" property="cid" jdbcType="INTEGER" />
      <result column="name" property="name" jdbcType="VARCHAR" />
      <result column="dec" property="dec" jdbcType="VARCHAR" />
    </collection>
</resultMap>

2.5.2 Course映射文件

<resultMap id="CourseMap" type="com.Course" >
    <id column="cid" property="cid" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="dec" property="dec" jdbcType="VARCHAR" />
    <collection property="students" ofType="com.Student">
      <id column="sid" property="sid" jdbcType="INTEGER" />
      <result column="sname" property="sname" jdbcType="VARCHAR" />
      <result column="hobit" property="hobit" jdbcType="VARCHAR" />
    </collection>
</resultMap>

2.5.3 CS映射文件

<resultMap id="CSMap" type="com.CS" >
        <id column="sc_id" property="sc_id" jdbcType="INTEGER" />
        <result column="grade" property="grade" jdbcType="VARCHAR" />
        <association property="student" javaType="com.Student">
            <id column="sid" property="sid" jdbcType="INTEGER" />
            <result column="sname" property="sname" jdbcType="VARCHAR" />
            <result column="hobit" property="hobit" jdbcType="VARCHAR" />
        </association>
        <association property="course" javaType="com.Course">
            <id column="cid" property="cid" jdbcType="INTEGER" />
            <result column="name" property="name" jdbcType="VARCHAR" />
            <result column="dec" property="dec" jdbcType="VARCHAR" />
        </association>
</resultMap>

2.6 编写SQL相应的语句

2.6.1 查询选修某课程的所有学生(一个Course对象里面有Student数组)

<select id="findById" parameterType="int" resultMap="CourseMap">
    select * from course c
    join course_student cs on c.cid=cs.cid
    join student s on cs.sid=s.sid
    where c.cid=#{id}
</select>

2.6.2 查询某学生查询的课程信息(一个Student对象里面有Course数组)

<select id="findById" parameterType="int" resultMap="StudentMap">
    select * from course c
    join course_student cs on c.cid=cs.cid
    join student s on cs.sid=s.sid
    where s.sid=#{id}
</select>

2.6.3 查询某学生某课程的成绩信息

<select id="findById" parameterType="map" resultMap="CSMap">
        select * from course c
        join course_student cs on c.cid=cs.cid
        join student s on cs.sid=s.sid
        where c.cid=#{cid} and s.sid=#{sid}
</select>

2.7 编写测试类

2.7.1 查询选修某课程的所有学生(一个Course对象里面有Student数组)

    @Test
    public void testCourse()
    {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            Course course=sqlSession.selectOne("com.CourseMapper.findById", 1);
            System.out.print(course);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            sqlSession.commit();
        }
        MyBatisUtil.closeSqlSession();
    }

2.7.2 运行结果

技术分享

2.7.3 查询某学生查询的课程信息(一个Student对象里面有Course数组)

     @Test
    public void testStudent()
    {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            Student student=sqlSession.selectOne("com.StudentMapper.findById", 1);
            System.out.print(student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            sqlSession.commit();
        }
        MyBatisUtil.closeSqlSession();
    }

2.7.4 运行结果

技术分享

2.7.5 查询某学生某课程的成绩信息

    @Test
     public void testCS()
    {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            Map<String,String> map=new HashMap<String,String>();
            map.put("cid","1");
            map.put("sid","1");
            CS cs=sqlSession.selectOne("com.CSMapper.findById", map);
            System.out.print(cs);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally{
            sqlSession.commit();
        }
        MyBatisUtil.closeSqlSession();
    }

2.7.6 运行结果

技术分享

3. 代码下载

本博客的代码下载地址为:MyBatis之多对多

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    (6)MyBatis之多对多关联