欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis入门(四)之多表操作

程序员文章站 2022-03-10 17:15:14
...

前期准备

在之前的项目基础上,我们只需要增加一个实体类Classes,添加变量和方法如下:

package com.stevensam.domain;

import java.util.Arrays;

/**
 * author:seven lin
 * date:2018/8/2719:25
 * description:班级实体
 **/
public class Classes {
    private int cid;
    private String cname;
    private int cnum;
    //封装本班的学生
    private List<Student> students;

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Classes{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", cnum=" + cnum +
                '}';
    }

    public int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public int getCnum() {
        return cnum;
    }

    public void setCnum(int cnum) {
        this.cnum = cnum;
    }
}

一、一对一(一对多)关系操作

  1. 一对一

    在IStudentDao接口中添加以下方法

    /**
    * 查询所有学生和对应的班级
    * @return
    */
    List<Student> findStudentAndClass();

    测试类中添加以下测试方法

    /**
    * 查询所有学生和对应班级
    */
    @Test
    public void testFindStudentAndClass() {
       //5.使用代理对象执行方法
       List<Student> studentList = iStudentDao.findStudentAndClass();
       for (Student stu : studentList) {
           System.out.println("-----------");
           System.out.println(stu);
           System.out.println(stu.getCla());
       }
    }

执行结果:

Mybatis入门(四)之多表操作

  1. 一对多

    创建IClassDao接口,代码如下

    package com.stevensam.dao;
    
    import com.stevensam.domain.Classes;
    import com.stevensam.domain.Classes;
    import java.util.List;
    
    /**
    * author:seven lin
    * date:2018/8/2319:31
    * description:班级接口
    **/
    public interface IClassDao {
    
       /**
        * 查询所有操作
        *
        * @return
        */
       List<Classes> findAll();
    
       /**
        * 查询所有班级和对应的学生
        *
        * @return
        */
       List<Classes> findClassAndStudent();
    
    }

    创建一个IClassDao.xml,代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
           PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
           "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.stevensam.dao.IClassDao">
    
       <resultMap id="classesMap" type="classes">
           <id property="cid" column="cid"></id>
           <result property="cname" column="cname"></result>
           <result property="cnum" column="cnum"></result>
           <!--一对多关系映射,用到是collection标签来封装-->
           <collection property="students" ofType="student">
               <id property="sid" column="sid"></id>
               <result property="sname" column="sname"></result>
               <result property="sex" column="sex"></result>
               <result property="birthday" column="birthday"></result>
               <result property="cno" column="cno"></result>
           </collection>
       </resultMap>
       <!--配置查询所有学生的方法-->
       <select id="findClassAndStudent" resultMap="classesMap">
         <!--select * FROM classes s,classes c WHERE s.cno = c.cid-->
           SELECT * from classes,student WHERE student.cno=classes.cid
       </select>
    </mapper>

    创建一个MybatisTest1测试类,代码如下:

    package com.stevensam.test;
    
    import com.stevensam.dao.IClassDao;
    import com.stevensam.domain.Classes;
    import com.stevensam.domain.Student;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.InputStream;
    import java.util.List;
    
    /**
    * author:seven lin
    * date:2018/8/2414:33
    * description:
    **/
    public class MybatisTest1 {
    
       private InputStream in;
       private SqlSession session;
       private IClassDao iclassDao;
    
       @Before//在测试方法之前执行
       public void init() throws Exception {
           //1.读取配置文件
           in = Resources.getResourceAsStream("SqlMapConfig.xml");
           //2.创建SqlSessionFactory工厂
           SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
           SqlSessionFactory factory = builder.build(in);
           //3.工厂生产SqlSession对象
           session = factory.openSession();
           //4.使用SqlSession创建Dao接口的代理对象
           iclassDao = session.getMapper(IClassDao.class);
       }
       @After//在测试方法之后执行
       public void destroy() throws Exception {
           //6.释放资源
           in.close();
           session.close();
       }
    
       /**
        * 查询所有班级和对应的学生
        */
       @Test
     public void testFindClassAndStudent() {
       //5.使用代理对象执行方法
       List<Classes> classesList = iclassDao.findClassAndStudent();
       for (Classes cla : classesList) {
         System.out.println(cla);
         System.out.println(cla.getStudents());
       }
     }
    }

执行结果:

Mybatis入门(四)之多表操作

二、多对多关系操作

​ 这次演示用的是学生选课,有学生表,课程表以及学生的选课表,在选课表中有对应的学生课程分数。这里只演示以学生为主来查询信息,以课程为主来查询就自行练习。

  1. 在数据库中建立一个课程表course以及学生选课表stu_course,代码如下:

    CREATE TABLE `course` (
     `cid` int(11) NOT NULL AUTO_INCREMENT,
     `cname` varchar(20) DEFAULT NULL,
     PRIMARY KEY (`cid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    CREATE TABLE `stu_course` (
     `scid` int(11) NOT NULL AUTO_INCREMENT,
     `sno` int(11) DEFAULT NULL,
     `cno` int(11) DEFAULT NULL,
     `score` int(11) DEFAULT NULL,
     PRIMARY KEY (`scid`),
     KEY `FK_stu_course_001` (`sno`),
     KEY `FK_stu_course_002` (`cno`),
     CONSTRAINT `FK_stu_course_001` FOREIGN KEY (`sno`) REFERENCES `student` (`sid`),
     CONSTRAINT `FK_stu_course_002` FOREIGN KEY (`cno`) REFERENCES `course` (`cid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;

    数据自行增加

  2. 分别增加实体类StuCourse和Course,代码如下:

    package com.stevensam.domain;
    
    /**
    * author:seven lin
    * date:2018/8/2820:51
    * description:学生选课表
    **/
    public class StuCourse {
       private int scid;
       private int sno;
       private int cno;
       private int score;
    
       @Override
       public String toString() {
           return "StuCourse{" +
                   "scid=" + scid +
                   ", sno=" + sno +
                   ", cno=" + cno +
                   ", score=" + score +
                   '}';
       }
    
       public int getScid() {
           return scid;
       }
    
       public void setScid(int scid) {
           this.scid = scid;
       }
    
       public int getSno() {
           return sno;
       }
    
       public void setSno(int sno) {
           this.sno = sno;
       }
    
       public int getCno() {
           return cno;
       }
    
       public void setCno(int cno) {
           this.cno = cno;
       }
    
       public int getScore() {
           return score;
       }
    
       public void setScore(int score) {
           this.score = score;
       }
    }
    package com.stevensam.domain;
    
    /**
    * author:seven lin
    * date:2018/8/2819:57
    * description:课程实体类
    **/
    public class Course {
    
       private int cid;
       private String cname;
    
       @Override
       public String toString() {
           return "Course{" +
                   "cid=" + cid +
                   ", cname='" + cname + '\'' +
                   '}';
       }
    
       public String getCname() {
           return cname;
       }
    
       public void setCname(String cname) {
           this.cname = cname;
       }
    
       public int getCid() {
    
           return cid;
       }
    
       public void setCid(int cid) {
           this.cid = cid;
       }
    }

  3. 在中添加成员变量和getset方法

    //学生所选课程
    private List<Course> courseList;
    //学生所选的课程分数类
    private List<StuCourse> stuCourseList;
    
    public List<StuCourse> getStuCourseList() {
     return stuCourseList;
    }
    
    public void setStuCourseList(List<StuCourse> stuCourseList) {
     this.stuCourseList = stuCourseList;
    }
    
    public List<Course> getCourseList() {
     return courseList;
    }
    
    public void setCourseList(List<Course> courseList) {
     this.courseList = courseList;
    }
  4. 还是在IStudentDao.xml中配置映射关系,添加以下代码:

    <resultMap id="stuCouMap" type="student">
     <id property="sid" column="sid"></id>
     <result property="sname" column="sname"></result>
     <result property="sex" column="sex"></result>
     <result property="birthday" column="birthday"></result>
     <result property="cno" column="cno"></result>
     <!--多对多关系映射-->
     <collection property="courseList" ofType="course">
       <id property="cid" column="cid"></id>
       <result property="cname" column="cname"></result>
     </collection>
     <collection property="stuCourseList" ofType="stucourse">
       <id property="scid" column="scid"></id>
       <result property="score" column="score"></result>
     </collection>
    </resultMap>
    <!----------------------------此处省略之前写的代码-------------------------->
    <!--配置查询所有学生和对应的课程的方法-->
       <select id="findStudentAndCourse" resultMap="stuCouMap">
           SELECT s.*,c.*,sc.score from student s
             LEFT OUTER JOIN stu_course sc ON sc.sno=s.sid
             LEFT OUTER JOIN course c ON sc.cno = c.cid
       </select>
  5. 在测试类MybatisTest中添加测试方法:

    /**
        * 查询所有学生和对应课程
        */
    @Test
    public void testFindStudentAndCourse() {
     //5.使用代理对象执行方法
     List<Student> classesList = iStudentDao.findStudentAndCourse();
     for (Student stu : classesList) {
       System.out.println("该学生对应的信息有:");
       System.out.println(stu);
       System.out.println(stu.getCourseList());
       System.out.println(stu.getStuCourseList());
     }
    }

    执行结果:
    Mybatis入门(四)之多表操作

相关标签: mybatis