Mybatis关联查询一对一和一对多的实现

Posted wuqi2328857945

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis关联查询一对一和一对多的实现相关的知识,希望对你有一定的参考价值。

Mybatis一对一关联查询

有两张表,老师表teacher和班级表class,一个class班级对应一个teacher,一个teacher对应一个class

需求是根据班级id查询班级信息(带老师的信息)

创建teacherclass表:

CREATE TABLE teacher (
        t_id INT PRIMARY KEY AUTO_INCREMENT,
        t_name VARCHAR(20)
    );
    CREATE TABLE class (
        c_id INT PRIMARY KEY AUTO_INCREMENT,
        c_name VARCHAR(20),
        teacher_id INT
    );
    ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES
    teacher(t_id);
    INSERT INTO teacher(t_name) VALUES(‘LS1‘);
    INSERT INTO teacher(t_name) VALUES(‘LS2‘);
    INSERT INTO class(c_name, teacher_id) VALUES(‘bj_a‘, 1);
    INSERT INTO class(c_name, teacher_id) VALUES(‘bj_b‘, 2);

首先定义实体类 
老师Teacher

package mybatis.bean;

    public class Teacher {

        private int id;
        private String name;

        public Teacher() {

        }

        public Teacher(int id, String name) {
            super();
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Teacher [id=" + id + ", name=" + name + "]";
        }



    }

班级Class

package mybatis.bean;

public class Class {

    private int id;
    private String name;
    private Teacher teacher;

    public Class() {
    }

    public Class(int id, String name, Teacher teacher) {
        super();
        this.id = id;
        this.name = name;
        this.teacher = teacher;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Class [id=" + id + ", name=" + name + ", teacher=" + teacher + "]";
    }





}

要实现一对一关联查询,有两种方式

1.关联表查询

SELECT * FROM class c, teacher t WHERE c.teacher_id = t.t_id AND c.c_id = 1;

2.执行2次查询 
先查询class表,获取teacher_id,再查询teacher表,获取teacher的信息

SELECT * FROM class where c_id = 1;
SELECT * FROM teacher where t_id = 1;//使用上面得到的teacher_id

这两种查询方式就引出了2中方式

  • 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
  • 嵌套查询:通过执行另外一个SQL 映射语句来返回预期的复杂类型

 

 

 

二、一对多关联

创建表和数据

  在上面的一对一关联查询演示中,我们已经创建了班级表和教师表,因此这里再创建一张学生表

 

CREATE TABLE student(
    s_id INT PRIMARY KEY AUTO_INCREMENT, 
    s_name VARCHAR(20), 
    class_id INT
);
INSERT INTO student(s_name, class_id) VALUES(‘student_A‘, 1);
INSERT INTO student(s_name, class_id) VALUES(‘student_B‘, 1);
INSERT INTO student(s_name, class_id) VALUES(‘student_C‘, 1);
INSERT INTO student(s_name, class_id) VALUES(‘student_D‘, 2);
INSERT INTO student(s_name, class_id) VALUES(‘student_E‘, 2);
INSERT INTO student(s_name, class_id) VALUES(‘student_F‘, 2);

定义实体类

  1、Student类

 

package me.gacl.domain;

/**
 * @author gacl
 * 定义student表所对应的实体类
 */
public class Student {

    //定义属性,和student表中的字段对应
    private int id;            //id===>s_id
    private String name;    //name===>s_name
    
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}

 

2、修改Classes类,添加一个List<Student> students属性,使用一个List<Student>集合属性表示班级拥有的学生,如下:

 

package me.gacl.domain;

import java.util.List;

/**
 * @author gacl
 * 定义class表对应的实体类
 */
public class Classes {

    //定义实体类的属性,与class表中的字段对应
    private int id;            //id===>c_id
    private String name;    //name===>c_name
    
    /**
     * class表中有一个teacher_id字段,所以在Classes类中定义一个teacher属性,
     * 用于维护teacher和class之间的一对一关系,通过这个teacher属性就可以知道这个班级是由哪个老师负责的
     */
    private Teacher teacher;
    //使用一个List<Student>集合属性表示班级拥有的学生
    private List<Student> students;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

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

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

    @Override
    public String toString() {
        return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher
                + ", students=" + students + "]";
    }
}

 

 

修改sql映射文件classMapper.xml

  添加如下的SQL映射信息

<!-- 
        根据classId查询对应的班级信息,包括学生,老师
     -->
    <!-- 
    方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
    SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND  c.c_id=1
     -->
    <select id="getClass3" parameterType="int" resultMap="ClassResultMap3">
        select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and  c.c_id=#{id}
    </select>
    <resultMap type="me.gacl.domain.Classes" id="ClassResultMap3">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
        <!-- ofType指定students集合中的对象类型 -->
        <collection property="students" ofType="me.gacl.domain.Student">
            <id property="id" column="s_id"/>
            <result property="name" column="s_name"/>
        </collection>
    </resultMap>
    
    <!-- 
        方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
            SELECT * FROM class WHERE c_id=1;
            SELECT * FROM teacher WHERE t_id=1   //1 是上一个查询得到的teacher_id的值
            SELECT * FROM student WHERE class_id=1  //1是第一个查询得到的c_id字段的值
     -->
     <select id="getClass4" parameterType="int" resultMap="ClassResultMap4">
        select * from class where c_id=#{id}
     </select>
     <resultMap type="me.gacl.domain.Classes" id="ClassResultMap4">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher" select="getTeacher2"></association>
        <collection property="students" ofType="me.gacl.domain.Student" column="c_id" select="getStudent"></collection>
     </resultMap>
     
     <select id="getTeacher2" parameterType="int" resultType="me.gacl.domain.Teacher">
        SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
     </select>
     
     <select id="getStudent" parameterType="int" resultType="me.gacl.domain.Student">
        SELECT s_id id, s_name name FROM student WHERE class_id=#{id}
     </select>

 

编写单元测试代码

package me.gacl.test;

import me.gacl.domain.Classes;
import me.gacl.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class Test4 {
    
    @Test
    public void testGetClass3(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.classMapper是classMapper.xml文件中mapper标签的namespace属性的值,
         * getClass3是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "me.gacl.mapping.classMapper.getClass3";//映射sql的标识字符串
        //执行查询操作,将查询结果自动封装成Classes对象返回
        Classes clazz = sqlSession.selectOne(statement,1);//查询class表中id为1的记录
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        //打印结果:Classes [id=1, name=class_a, teacher=Teacher [id=1, name=teacher1], students=[Student [id=1, name=student_A], Student [id=2, name=student_B], Student [id=3, name=student_C]]]
        System.out.println(clazz);
    }
    
    @Test
    public void testGetClass4(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.classMapper是classMapper.xml文件中mapper标签的namespace属性的值,
         * getClass4是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        String statement = "me.gacl.mapping.classMapper.getClass4";//映射sql的标识字符串
        //执行查询操作,将查询结果自动封装成Classes对象返回
        Classes clazz = sqlSession.selectOne(statement,1);//查询class表中id为1的记录
        //使用SqlSession执行完SQL之后需要关闭SqlSession
        sqlSession.close();
        //打印结果:Classes [id=1, name=class_a, teacher=Teacher [id=1, name=teacher1], students=[Student [id=1, name=student_A], Student [id=2, name=student_B], Student [id=3, name=student_C]]]
        System.out.println(clazz);
    }
}

 



以上是关于Mybatis关联查询一对一和一对多的实现的主要内容,如果未能解决你的问题,请参考以下文章

mybatis笔试题2

MyBatis高级篇 - 关联查询(一对多)

Mybatis的嵌套关联查询案例实战

MyBatis总结之高级映射一对多查询

MyBatis学习09高级映射之一对多查询

mybatis关联查询,一对一,一对多