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 */ ; -- ---------------------------- -- 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框架——多表查询的更多相关文章
- MyBatis框架——单表查询
Mybatis单表查询,示例 1.创建数据库 /* Navicat MySQL Data Transfer Source Server : localhost Source Server Versio ...
- Mybatis框架-联表查询显示问题解决
需求:查询结果要求显示用户名,用户密码,用户的角色 因为在用户表中只有用户角色码值,没有对应的名称,角色名称是在码表smbms_role表中,这时我们就需要联表查询了. 这里需要在User实体类中添加 ...
- Yii框架 多表查询实例
Yii框架多表查询实例:总共分为两个步骤(以下的代码我全部都写在model中):1.先在主表model中声明关联表中所需要查询的字段. public $surveyls_description; // ...
- 使用Mybatis进行连表查询、left join---https://blog.csdn.net/jinzhencs/article/details/51980518
使用Mybatis进行连表查询.left join https://blog.csdn.net/jinzhencs/article/details/51980518
- SpringBoot集成Mybatis实现多表查询的两种方式(基于xml)
下面将在用户和账户进行一对一查询的基础上进行介绍SpringBoot集成Mybatis实现多表查询的基于xml的两种方式. 首先我们先创建两个数据库表,分别是user用户表和account账户表 ...
- MyBatis的多表查询笔记
MyBatis的多表查询 随着学习的进步,需求的提高,我们在实际开发中用的最多的还是多表查询,就让我们一起学习MyBatis中的多表查询. 数据库准备 Class表 Student表 项目结构 这次使 ...
- 07 Mybatis的多表查询1----1对多和多对1---@Results注解用法总结
1.表与表之间的关系及其举例 表之间的关系有4种:一对多.多对一.一对一.多对多. 举例: (1)用户和订单就是一对多 一个用户可以下多个订单 (2)订单和用户就是多对一 多个订单属于同一个用户 (3 ...
- mybatis之联表查询
今天碰到了一个问题,就是要在三张表里面各取一部分数据然后组成一个list传到前台页面显示.但是并不想在后台做太多判断,(因为涉及到for循环)会拉慢运行速度.正好用的框架是spring+springM ...
- MyBatis实现关联表查询
一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...
随机推荐
- Rancher安装多节点高可用(HA)
Rancher版本:Rancher v1.0.1 基本配置需求 多节点的HA配置请参照单节点需求 节点需要开放的端口 全局访问:TCP 端口22,80,443,18080(可选:用于在集群启动前 查看 ...
- LG_2869_[USACO07DEC]美食的食草动物Gourmet Grazers
题目描述 Like so many others, the cows have developed very haughty tastes and will no longer graze on ju ...
- 实战:CentOS 7.2 / Zabbix3.4安装graphtrees
众所周知的 Zabbix图形显示问题,决定使用graphtrees 插件. 环境:CentOS7.2 + Zabbix 3.4 1)首先切换到root用户以获得足够的权限将资源下载到 /usr/sha ...
- axios 传对象(JavaBean)到后台
//user对象 let user = JSON.stringify({ userAccountNumber: own.userName, userPassword: own.userPassword ...
- 基于seo的话 一个页面里的h1标签应该控制在多少个
不能出现多个,一个页面只能出现一次,次数多了就会造成权重分散
- 在python中使用json
在服务器和客户端的数据交互的时候,要找到一种数据格式,服务端好处理,客户端也好处理,这种数据格式应该是一种统一的标准,不管在哪里端处理起来都是统一的,现在这种数据格式非常的多,比如最早的xml,再后来 ...
- 用java实现的微信公众号爬虫
Published: 2016-11-23 In Spider. tags: Spider 版权声明:本文为博主原创文章,未经博主允许不得转载. 思路: 直接从chuansong.me爬取,由于微信公 ...
- Class file version does not support constant tag 16 in class file
启动服务时提示 Caused by: java.lang.ClassFormatError: Class file version does not support constant tag 16 i ...
- ADO.NET中DataTable类的使用
DataTable类将关系数据表示为表格形式.在创建DataTable之前,必须包含System.Data名称空间.ADO.NET提供了一个DataTable类来独立创建和使用数据表.它也可以和Dat ...
- MySQL基础篇(05):逻辑架构图解和InnoDB存储引擎详解
本文源码:GitHub·点这里 || GitEE·点这里 一.MySQL逻辑架构 1.逻辑架构图 基于下面的逻辑架构图,可以大致熟悉MySQL各个架构组件之间的协同工作关系. 很经典的C/S架构风格, ...