多表关联查询时,返回主表全部数据

Posted

tags:

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

参考技术A 1、这里主表有8条数据

2、错误写法
由于表连接后紧接where条件过滤,所以主表数据没有全部显示。

结果:只查出3条主表数据

3、正确写法

结果:主表数据全部查出

MyBatis框架——多表查询

MyBatis多表查询,

  从表中映射主表,使用 association 标签,通过设置 javaType 属性关联实体类;

  主表映射从表,使用 collection 标签,通过 ofType 属性关联实体类。 

 

示例:

 

1、创建数据库

/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50620
Source Host           : 127.0.0.1:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50620
File Encoding         : 65001

Date: 2020-03-22 16:50:26
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES (1, 1班);
INSERT INTO `classes` VALUES (2, 2班);
INSERT INTO `classes` VALUES (3, 3班);
INSERT INTO `classes` VALUES (4, 4班);

-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES (1, java);
INSERT INTO `course` VALUES (2, python);

-- ----------------------------
-- Table structure for course_student
-- ----------------------------
DROP TABLE IF EXISTS `course_student`;
CREATE TABLE `course_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sid` int(11) NOT NULL,
  `cid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `sid` (`sid`),
  KEY `cid` (`cid`),
  CONSTRAINT `course_student_ibfk_1` FOREIGN KEY (`sid`) REFERENCES `student` (`id`),
  CONSTRAINT `course_student_ibfk_3` FOREIGN KEY (`cid`) REFERENCES `course` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course_student
-- ----------------------------
INSERT INTO `course_student` VALUES (1, 1, 2);

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `cid` int(11) NOT NULL,
  `score` varchar(255) DEFAULT NULL,
  `tel` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, 张三, 2, 90, 15510211111, 大望路);
INSERT INTO `student` VALUES (2, 李四, 3, 91, 13502020303, 知春路);
INSERT INTO `student` VALUES (3, 赵六, 2, 87, 18800110011, 回龙观);

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, 张三1, 1234567, 88);
INSERT INTO `t_user` VALUES (2, 张三, 321, 33);
INSERT INTO `t_user` VALUES (6, 王五2, 123456, 19);

 

2、编写实体类

package com.sunjian.entity;

/**
 * @author sunjian
 * @date 2020/3/22 14:21
 */
public class Student {
    private Integer id;
    private String name;
    private Integer score;
    private String tel;
    private String address;
    private Classes classes;
    private Course course;

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=‘" + name + ‘‘‘ +
                ", score=" + score +
                ", tel=‘" + tel + ‘‘‘ +
                ", address=‘" + address + ‘‘‘ +
                ", classes=" + classes +
                ", course=" + course +
                ‘}‘;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

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

    public Integer getScore() {
        return score;
    }

    public void setScore(Integer score) {
        this.score = score;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }
}
package com.sunjian.entity;

import java.util.List;

/**
 * @author sunjian
 * @date 2020/3/22 14:20
 */
public class Classes {
    private Integer id;
    private String name;
    private List<Student> students;

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

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

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

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.sunjian.entity;

import java.util.List;

/**
 * @author sunjian
 * @date 2020/3/22 15:53
 */
public class Course {
    private Integer id;
    private String name;
    private List<Student> students;
    private Classes classes;

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

    @Override
    public String toString() {
        return "Course{" +
                "id=" + id +
                ", name=‘" + name + ‘‘‘ +
                ", students=" + students +
                ", classes=" + classes +
                ‘}‘;
    }

    public Integer getId() {
        return id;
    }

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

    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;
    }
}

 

3、编写repository接口

package com.sunjian.repository;

import com.sunjian.entity.Student;

/** 一对一
 * @author sunjian
 * @date 2020/3/22 14:33
 */
public interface StudentRepository {
    public Student findStudentById(Integer id);
}
package com.sunjian.repository;

import com.sunjian.entity.Classes;
import com.sunjian.entity.Student;

import java.util.List;

/** 一对多
 * @author sunjian
 * @date 2020/3/22 15:07
 */
public interface ClassesRepository {
    public Classes findClassById(Integer id);
}
package com.sunjian.repository;

import com.sunjian.entity.Course;

/** 多对多
 * @author sunjian
 * @date 2020/3/22 15:56
 */
public interface CourseRepository {
    public Course findCourseById(Integer id);
}

 

4、编写mapper.xml文件

StudentRepository.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.sunjian.repository.StudentRepository">

    <!-- 一对一 -->
    <resultMap id="studentMap" type="com.sunjian.entity.Student">
        <id property="id" column="sid"></id>
        <result property="name" column="sname"></result>
        <result property="score" column="score"></result>
        <result property="tel" column="tel"></result>
        <result property="address" column="address"></result>
        <association property="classes" javaType="com.sunjian.entity.Classes">
            <id property="id" column="cid"></id>
            <result property="name" column="cname"></result>
        </association>
    </resultMap>

    <select id="findStudentById" parameterType="java.lang.Integer" resultMap="studentMap">
        select s.id sid, s.name sname, s.score, s.tel, s.address, c.id cid, c.name cname from student s, classes c where s.cid = c.id and s.id = #{id}
    </select>
</mapper>

ClassesRepository.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.sunjian.repository.ClassesRepository">
    
    <!-- 一对多 -->
    <resultMap id="classMap" type="com.sunjian.entity.Classes">
        <id property="id" column="cid"></id>
        <result property="name" column="cname"></result>
        <collection property="students" ofType="com.sunjian.entity.Student">
            <id property="id" column="sid"></id>
            <result property="name" column="sname"></result>
            <result property="score" column="score"></result>
            <result property="tel" column="tel"></result>
            <result property="address" column="address"></result>
        </collection>
    </resultMap>

   <select id="findClassById" parameterType="java.lang.Integer" resultMap="classMap">
       select c.id cid, c.name cname, s.id sid, s.name sname, s.score, s.tel, s.address from classes c, student s where s.cid = c.id and c.id = #{id}
   </select>
</mapper>

CourseRepository.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.sunjian.repository.CourseRepository">
    
    <!-- 多对多 -->
    <resultMap id="courseMap" type="com.sunjian.entity.Course">
        <id property="id" column="courseid"></id>
        <result property="name" column="coursename"></result>
        <collection property="students" ofType="com.sunjian.entity.Student">
            <id property="id" column="sid"></id>
            <result property="name" column="sname"></result>
            <result property="score" column="score"></result>
            <result property="tel" column="tel"></result>
            <result property="address" column="address"></result>
        </collection>
        <collection property="classes" ofType="com.sunjian.entity.Classes">
            <id property="id" column="classid"></id>
            <result property="name" column="classname"></result>
        </collection>
    </resultMap>

   <select id="findCourseById" parameterType="java.lang.Integer" resultMap="courseMap">
        select s.id sid, s.name sname, score, tel, address, c.id courseid, c.name coursename, cl.id classid, cl.name classname from student s, course c, classes cl, course_student cs where cl.id = s.cid and cs.sid = s.id and cs.cid = c.id and c.id = #{id};
   </select>
</mapper>

 

5、在resources下编写全局config.xml文件,将mapper.xml注册到config.xml文件中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- 配置 MyBatis 数据源 -->
    <environments default="development">
        <environment id="development">
            <!-- JDBC事务管理 -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 注册 -->
    <mappers>
        <!-- 单表 -->
        <mapper resource="com/sunjian/mapper/UserMapper.xml"></mapper>
        <mapper resource="com/sunjian/repository/UserRepository.xml"></mapper>

        <!-- 多表 一对一 -->
        <mapper resource="com/sunjian/repository/StudentRepository.xml"></mapper>
        <!-- 多表 一对多 -->
        <mapper resource="com/sunjian/repository/ClassesRepository.xml"></mapper>
        <!-- 多表 多对多 -->
        <mapper resource="com/sunjian/repository/CourseRepository.xml"></mapper>
    </mappers>

</configuration>

 

6、编写测试类

package com.sunjian.test;

import com.sunjian.entity.Classes;
import com.sunjian.entity.Course;
import com.sunjian.entity.Student;
import com.sunjian.repository.ClassesRepository;
import com.sunjian.repository.CourseRepository;
import com.sunjian.repository.StudentRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author sunjian
 * @date 2020/3/22 14:40
 */
public class TestMoreTable {
    public static void main(String[] args) {
        InputStream inputStream = Student.class.getClassLoader().getResourceAsStream("config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 一对一
        StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
        Student student = studentRepository.findStudentById(2);
        System.out.println(student);

        // 一对多
        ClassesRepository classesRepository = sqlSession.getMapper(ClassesRepository.class);
        Classes classes = classesRepository.findClassById(2);
        System.out.println(classes);

        // 多对多
        CourseRepository courseRepository = sqlSession.getMapper(CourseRepository.class);
        Course course = courseRepository.findCourseById(2);
        System.out.println(course);
    }
}
Student{id=2, name=‘李四‘, score=91, tel=‘13502020303‘, address=‘知春路‘, classes=Classes{id=3, name=‘3班‘, students=null}, course=null}
Classes{id=2, name=‘2班‘, students=[Student{id=1, name=‘张三‘, score=90, tel=‘15510211111‘, address=‘大望路‘, classes=null, course=null}, Student{id=3, name=‘赵六‘, score=87, tel=‘18800110011‘, address=‘回龙观‘, classes=null, course=null}]}
Course{id=2, name=‘python‘, students=[Student{id=1, name=‘张三‘, score=90, tel=‘15510211111‘, address=‘大望路‘, classes=null, course=null}], classes=Classes{id=2, name=‘2班‘, students=null}}

 

 

 

 

OK.

以上是关于多表关联查询时,返回主表全部数据的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis框架——多表查询

多表关联查询语法?

Oracle多表连接查询Join

多表关联

jpa的一些个人总结(多表查询的坑)

MySQL — 关联