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
*/

;

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

-- ----------------------------
-- Records of classes
-- ----------------------------
', '1班');
', '2班');
', '3班');
', '4班');

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

-- ----------------------------
-- Records of course
-- ----------------------------
', 'java');
', 'python');

-- ----------------------------
-- Table structure for course_student
-- ----------------------------
DROP TABLE IF EXISTS `course_student`;
CREATE TABLE `course_student` (
  `id` ) NOT NULL AUTO_INCREMENT,
  `sid` ) NOT NULL,
  `cid` ) 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 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course_student
-- ----------------------------
');

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

-- ----------------------------
-- Records of student
-- ----------------------------
', '大望路');
', '知春路');
', '回龙观');

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

-- ----------------------------
-- Records of t_user
-- ----------------------------
');
');
');

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框架——多表查询的更多相关文章

  1. MyBatis框架——单表查询

    Mybatis单表查询,示例 1.创建数据库 /* Navicat MySQL Data Transfer Source Server : localhost Source Server Versio ...

  2. Mybatis框架-联表查询显示问题解决

    需求:查询结果要求显示用户名,用户密码,用户的角色 因为在用户表中只有用户角色码值,没有对应的名称,角色名称是在码表smbms_role表中,这时我们就需要联表查询了. 这里需要在User实体类中添加 ...

  3. Yii框架 多表查询实例

    Yii框架多表查询实例:总共分为两个步骤(以下的代码我全部都写在model中):1.先在主表model中声明关联表中所需要查询的字段. public $surveyls_description; // ...

  4. 使用Mybatis进行连表查询、left join---https://blog.csdn.net/jinzhencs/article/details/51980518

    使用Mybatis进行连表查询.left join https://blog.csdn.net/jinzhencs/article/details/51980518

  5. SpringBoot集成Mybatis实现多表查询的两种方式(基于xml)

     下面将在用户和账户进行一对一查询的基础上进行介绍SpringBoot集成Mybatis实现多表查询的基于xml的两种方式.   首先我们先创建两个数据库表,分别是user用户表和account账户表 ...

  6. MyBatis的多表查询笔记

    MyBatis的多表查询 随着学习的进步,需求的提高,我们在实际开发中用的最多的还是多表查询,就让我们一起学习MyBatis中的多表查询. 数据库准备 Class表 Student表 项目结构 这次使 ...

  7. 07 Mybatis的多表查询1----1对多和多对1---@Results注解用法总结

    1.表与表之间的关系及其举例 表之间的关系有4种:一对多.多对一.一对一.多对多. 举例: (1)用户和订单就是一对多 一个用户可以下多个订单 (2)订单和用户就是多对一 多个订单属于同一个用户 (3 ...

  8. mybatis之联表查询

    今天碰到了一个问题,就是要在三张表里面各取一部分数据然后组成一个list传到前台页面显示.但是并不想在后台做太多判断,(因为涉及到for循环)会拉慢运行速度.正好用的框架是spring+springM ...

  9. MyBatis实现关联表查询

    一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...

随机推荐

  1. Python如何让字典保持有序

    问题: Python如何让字典保持有序 ? 解决方案: 使用collections.OrderedDict代替Dict. 验证程序: from collections import OrderedDi ...

  2. 成为数据专家,你只差一个Quick Insights的距离

    身处如今的大数据时代,你真的知道如何处理数据和分析数据吗?或许那些被你忽视的数据背后就暗藏着重要的商业灵感.并非人人都是数据专家,有时候你需要一些专业的软件来帮你处理数据.那么如何能快速.准确地从数据 ...

  3. ckeditor 捕获键代码

    <!--<script type="text/javascript"> var ctrlKey = false; var shiftKey = false; if ...

  4. oracle监控参数

    Sar –u 检查CPU的繁忙程度列说明Usr用户模式下cpu运行所占的百分比Sys系统模式下cpu运行所占的百分比Wio因为有进程等待块I/O而使cpu处于闲置状态所占百分比IdleCpu为闲置状态 ...

  5. Javascript学习笔记-基本概念-函数

    ECMAScript 中的函数使用function 关键字来声明,后跟一组参数以及函数体.函数的基本语法如下所示: function functionName(arg0, arg1,...,argN) ...

  6. SQL基本操作总结

    1.SQL简介 结构化查询语言 (层次模型,网状模型,关系模型) 关系模型是目前的主流 (Oralce,mysql mssql ) SQL标准:ANSI (1992 1997 2002 ISO) 方言 ...

  7. 利用ajax 引入静态页公共的头部与底部

    利用ajax引入公共的头部与底部或者多个页面需要用到的重复的组件,对于新入门的前端来说是很实用的方法,自己也是新手菜鸟一枚,折腾了好久,实现的方法有很多种,这是我个人觉得比较简单方便的 首先得把公用的 ...

  8. webpack从0到1超详细超基础学习教程

    概念 自己是一个一听到webpack就头大,看着一堆不知道那是什么玩意的东西总觉得自己做好前端就行了,但是在使用vue-cli的时候总觉得要改其中的一些东西进行项目初始化的时候能够更好使用!所以想要根 ...

  9. spring——AOP原理及源码(五)

    前情回顾: 在上一篇中,通过 wrapIfNecessary 方法,我们获取到了合适的增强器(日志方法)与业务类进行包装,最终返回了我们业务类的代理对象. 本篇我们将从业务方法的执行开始,看看增强器( ...

  10. JavaScript的数组系列

    数组 今天逆战班的学习主题关于Javascript的数组,主要有数组的概念.创建.分类.方法.遍历.经典算法...... 一.数组是什么呢?怎么写数组呢?数组有多少种呢? 数组的概念 对象是属性的无序 ...