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.

原文地址:https://www.cnblogs.com/zuichao123/p/12546962.html

时间: 2024-10-11 09:09:11

MyBatis框架——多表查询的相关文章

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

 下面将在用户和账户进行一对一查询的基础上进行介绍SpringBoot集成Mybatis实现多表查询的基于xml的两种方式.   首先我们先创建两个数据库表,分别是user用户表和account账户表     user表:  account表:  然后创建实体类        **第一种通过创建子类的方式查询                             需求:查询所有的用户基础信息以及其所属的账户中的金额     1.创建想要得到多表查询数据的实体类(子类)            

mybatis之联表查询

今天碰到了一个问题,就是要在三张表里面各取一部分数据然后组成一个list传到前台页面显示.但是并不想在后台做太多判断,(因为涉及到for循环)会拉慢运行速度.正好用的框架是spring+springMVC+mybatis,所以很自然的就想到了联表查询. 一开始认为mybatis编写语句很简单,但是在编写的时候遇到了一些细节问题,所以发文记录一下. 先说一下背景: 框架:spring+springMVC+mybatis 表结构: 1.主表 2.从表 从表的uid对应主表的id,并将主表的id设为主

Mybatis实现关联表查询

一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关系. 1 CREATE TABLE teacher( 2 t_id INT PRIMARY KEY AUTO_INCREMENT, 3 t_name VARCHAR(20) 4 ); 5 CREATE TABLE class( 6 c_id INT PRIMARY KEY AUTO_INCREMEN

MyBatis——实现关联表查询

原文:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关系. CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) ); CREATE TABLE cla

Mybatis 实现关联表查询

一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关系. 1 CREATE TABLE teacher( 2 t_id INT PRIMARY KEY AUTO_INCREMENT, 3 t_name VARCHAR(20) 4 ); 5 CREATE TABLE class( 6 c_id INT PRIMARY KEY AUTO_INCREMEN

mybatis一对一关联表查询

先创建一个表 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

MyBatis(跨表查询)

1.建立数据库表如下: DROP TABLE IF EXISTS t_demo_user; CREATE TABLE IF NOT EXISTS t_demo_user( userid varchar(255), username varchar(100), password varchar(100), PRIMARY KEY(userid) )ENGINE=InnoDB DEFAULT CHARSET=gbk; insert into t_demo_user(userid, username,

Mybatis框架的模糊查询(多种写法)、删除、添加

学习Mybatis这么多天,那么我给大家分享一下我的学习成果.从最基础的开始配置. 一.创建一个web项目,看一下项目架构 二.说道项目就会想到需要什么jar 三.就是准备大配置链接Orcl数据库 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "htt

Spring+MyBatis框架中sql语句的书写,数据集的传递以及多表关联查询

在很多Java EE项目中,Spring+MyBatis框架经常被用到,项目搭建在这里不再赘述,现在要将的是如何在项目中书写,增删改查的语句,如何操作数据库,以及后台如何获取数据,如何进行关联查询,以及MyBatis的分页问题. 首先先看看项目的架构,方便后边叙述. 这个项目中是一个Sping+MyBatis的完整demo(这边将页面没有展示.)这次的主题主要是后台数据处理逻辑.接下来为大家逐一介绍各个文件, org.config   Spring配置包括数据库的链接信息 org.control