Mybatis se da cuenta del uso de consultas de tabla combinadas y consultas anidadas (uno a muchos, muchos a uno) y mapeo de conjuntos de resultados

0, construcción ambiental

Hay dos conjuntos de entidades: alumno y maestro. Suponga que la relación entre el alumno y el maestro consejero es que un maestro enseña a varios alumnos y un alumno solo tiene un maestro consejero. Cree tablas, cree proyectos maven, importe dependencias, escriba archivos de configuración, etc.

1. Muchos a uno

Un estudiante tiene solo un profesor consejero, entonces la clase de entidad del estudiante (pojo, javabean) se puede escribir así

package com.wt.pojo;

public class Student {
    
    
    private int id;
    private String name;
    private Teacher teacher;

    public Student() {
    
    
    }

    public Student(int id, String name, Teacher teacher) {
    
    
        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;
    }
}

La clase de entidad del profesor se puede escribir así

package com.wt.pojo;

public class Teacher {
    
    
    private int tid;
    private String name;

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

    public Teacher() {
    
    

    }

    public int getTid() {
    
    
        return tid;
    }

    public void setTid(int tid) {
    
    
        this.tid = tid;
    }

    public String getName() {
    
    
        return name;
    }

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

Interfaz del alumno, consulte las notas para las preguntas

package com.wt.mapper;

import com.wt.pojo.Student;

import java.util.List;

public interface StudentMapper {
    
    

    //想要实现这样的select语句:
    //select student.id,student.name,teacher.name
    //from student,teacher
    //where student.tid=teacher.id
    //如果直接执行是查不出的,必须再=在配置文件中“模拟”联表查询或嵌套查询

    //获得所有学生,模拟嵌套查询
    List<Student> getAllStudents01();
    //获得所有学生,模拟联表查询
    List<Student> getAllStudents02();
}

Vinculando el archivo de configuración de la interfaz del estudiante, la realización del problema y los puntos que necesitan atención, vea los comentarios (el uso del mapeo del conjunto de resultados también está en los comentarios). Se implementan los siguientes métodos de tabla de anidación y unión de código.

<?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.wt.mapper.StudentMapper">
    <!--resultMap是结果集映射,这个需要在下面再写一个resultMap标签来完成结果集映射,当然resultMap的id要对好-->
    <select id="getAllStudents01" resultMap="StudentTeacher01">
        select * from mybatis.student;
    </select>
    <!--下面的结果集映射将Student中的属性(property)与表中的列(column)相映射起来-->
    <resultMap id="StudentTeacher01" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--对于简单的属性,直接写映射关系就好了,甚至不写也可以,mybatis会自动帮你对应(有前提)-->
        <!--对于复杂的属性,比如引用,就得用association或者collection了,用法参照下面-->
        <!--Student中的teacher属性是个引用,想要查询到,就得嵌套其他的查询-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
    </resultMap>
    <!--下面这个查询标签的id对应第16行中的select的值,所以这个查询会被上面“调用”,参数也会自动传递(比如这里的tid)-->
    <select id="getTeacherById" resultType="Teacher">
        select * from mybatis.teacher where id = #{tid};
    </select>
    <!--以上的三个标签实现了嵌套查询-->
    <!--=====================================另一种方式(类似联表查询)=====================================-->
    <select id="getAllStudents02" resultMap="StudentTeacher02">
        select student.id sid,student.name sname,teacher.name tname
        from student,teacher
        where student.tid=teacher.id
    </select>
    <resultMap id="StudentTeacher02" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

</mapper>

Código de prueba

    @org.junit.Test
    public void test00(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> students = studentMapper.getAllStudents01();
        for(Student student:students){
    
    
            System.out.print(student.getId());
            System.out.print(" ");
            System.out.println(student.getTeacher().getName());
        }
        System.out.println("--------------------------------");
        List<Student> students2 = studentMapper.getAllStudents02();
        for(Student student:students2){
    
    
            System.out.print(student.getId());
            System.out.print(" ");
            System.out.println(student.getTeacher().getName());
        }
        
        sqlSession.close();

    }

2. Muchos a uno

La clase de entidad del profesor se puede escribir así

package com.wt.pojo;

import java.util.List;

public class Teacher {
    
    
    private int tid;
    private String name;
    private List<Student> students;

    public Teacher() {
    
    

    }

    public Teacher(int tid, String name, List<Student> students) {
    
    
        this.tid = tid;
        this.name = name;
        this.students = students;
    }

    public int getTid() {
    
    
        return tid;
    }

    public void setTid(int tid) {
    
    
        this.tid = tid;
    }

    public String getName() {
    
    
        return name;
    }

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

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

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

La clase de entidad de estudiante se puede escribir así

package com.wt.pojo;

public class Student {
    
    
    private int id;
    private String name;
    private int tid;

    public Student() {
    
    
    }

    public Student(int id, String name, int tid) {
    
    
        this.id = id;
        this.name = name;
        this.tid = tid;
    }

    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 int getTid() {
    
    
        return tid;
    }

    public void setTid(int tid) {
    
    
        this.tid = tid;
    }
}

Interfaz del profesor

package com.wt.mapper;

import com.wt.pojo.Student;
import com.wt.pojo.Teacher;

import java.util.List;

public interface TeacherMapper {
    
    
    //需求:根据老师的id查询出其所教的所有学生
    List<Student> getStudentsOfTeacherByTeacherId();

    //列出学生的同时列出老师
    Teacher getTeacherAndHerStudents(int tid);
}

Vinculando el archivo de configuración de la interfaz del profesor, preste atención a las notas, la mayoría de las cuales son similares a uno a muchos

<?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.wt.mapper.TeacherMapper">
    <select id="getStudentsOfTeacherByTeacherId" resultMap="TeacherStudent">
        select student.id sid,student.name sname from student,teacher where student.tid=teacher.id and teacher.id=1;
    </select>
    <resultMap id="TeacherStudent" type="Student">
        <result property="name" column="sname"/>
        <result property="id" column="sid"/>
    </resultMap>

    <select id="getTeacherAndHerStudents" resultMap="TeacherStudent2">
        select student.id sid,student.name sname,teacher.name tname
        from student,teacher
        where student.tid=teacher.id and teacher.id=#{tid}
    </select>
    <resultMap id="TeacherStudent2" type="Teacher">
        <result property="name" column="tname"/>
        <!--老师拥有一个列表的学生,用collection来表示这个属性,collection中的Type不是javaType而是ofType-->
        <collection property="students" ofType="Student">
            <result property="name" column="sname"/>
            <result property="id" column="sid"/>
        </collection>
    </resultMap>

</mapper>

prueba

    @org.junit.Test
    public void test01(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        List<Student> students = teacherMapper.getStudentsOfTeacherByTeacherId();
        for(Student student:students){
    
    
            System.out.println(student.getName());
        }
        sqlSession.close();
    }

    @org.junit.Test
    public void test02(){
    
    
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper teacherMapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = teacherMapper.getTeacherAndHerStudents(1);
        for(Student student:teacher.getStudents()){
    
    
            System.out.print(student.getId());
            System.out.print(student.getName());
            System.out.println(teacher.getName());
            System.out.println("--------------------------------");
        }
        sqlSession.close();
    }

Supongo que te gusta

Origin blog.csdn.net/kitahiragawa/article/details/113062640
Recomendado
Clasificación