MyBatis 多表操作的实现

1.1 一对一查询

1.1.1 概述

  关系数据库中第一个表中的单个行只可以与第二个表中的一个行相关,且第二个表中的一个行也只可以与第一个表中的一个行相关。

1.1.2 创建实体类

public class Student {
  private Integer id;
  private String name;
  private Boolean age;
  private String sex;
  private StudentStatus studentStatus;

  // set and get
}
public class StudentStatus {
  private Integer id;
  private String num;
  private String major;

  // set and get
}

1.1.3 创建 DAO 接口

public class StudentStatus {
  private Integer id;
  private String num;
  private String major;

  // set and get
}

1.1.4 结果映射

  resultMap 元素是 MyBatis 中最重要最强大的元素。它可以从 90% 的 JDBC ResultSets 数据提取代码中解放出来,并在一些情形下允许进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap 能够代替实现同等功能的长达数千行的代码。resultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。之前已经使用过简单映射语句了,但并没有显式指定 resultMap。只是简单的使用 resultType 将所有的列映射到对象的属性上,需要注意的是列名与属性名一致才能映射,解决列名不匹配还是需要使用 resultMap。

<resultMap id="userResultMap" type="User">
	<result property="id" column="user_id" />
	<result property="username" column="user_name"/>
	<result property="password" column="hashed_password"/>
</resultMap>
<select id="selectUsers" resultMap="userResultMap">
	select user_id, user_name, hashed_password from some_table where id = #{id}
</select>

1.1.5 配置 mapper

<?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.software.mybatis.dao.StudentDao">
  <resultMap id="resMap" type="student">
    <result property="studentStatus.id" column="st_id"/>
    <result property="studentStatus.major" column="major"/>
    <result property="studentStatus.num" column="num"/>
  </resultMap>
  <select id="findAll" resultMap="resMap">
    select * from student s, student_status st where s.st_id = st.st_id
  </select>
</mapper>

上面这种配置会将自动将列名一致的映射到 type 指定的实体类中,该实体类中属性类型为对象的则需要单独拿出来映射。还可以使用 association 进行复杂的映射,我们发现未配置的属性无法进行映射。产生这个问题的原因是 resultMap 的自动映射未打开,使用 autoMapping 设置这个属性为 true/false,MyBatis 将会为本结果映射开启/关闭自动映射。

<mapper namespace="com.software.mybatis.dao.StudentDao">
  <resultMap id="resMap" type="com.software.mybatis.entity.Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="sex" column="sex"/>
    <result property="age" column="age"/>
    <association property="studentStatus" javaType="com.software.mybatis.entity.StudentStatus">
      <result property="id" column="st_id"/>
      <result property="major" column="major"/>
      <result property="num" column="num"/>
    </association>
  </resultMap>
  <select id="findAll" resultMap="resMap">
    select * from student s, student_status st where s.st_id = st.st_id
  </select>
</mapper>
<?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.software.mybatis.dao.StudentDao">
  <resultMap id="resMap" type="student" autoMapping="true">
    <association property="studentStatus" resultMap="stMap" />
  </resultMap>
  <resultMap id="stMap" type="StudentStatus" autoMapping="true"/>
  <select id="findAll" resultMap="resMap">
    select * from student s, student_status st where s.st_id = st.st_id
  </select>
</mapper>

1.1.6 核心配置

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

  <settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
  </settings>

  <typeAliases>
    <package name="com.software.mybatis.entity"/>
  </typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="student-mapper.xml"/>
  </mappers>

</configuration>

1.1.7 测试

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description 测试类
 */
public class MybatisDemo {

  @Test
  public void TestA() throws IOException {
    // 加载核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
    // 获得 sqlSession 工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    // 获得 sqlSession 对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    List<Student> list = sqlSession.selectList("com.software.mybatis.dao.StudentDao.findAll");

    System.out.println(list);
  }
}

1.2 一对多查询

1.2.1 概述

  一对多关系是关系数据库中两个表之间的一种关系,该关系中第一个表中的单个行可以与第二个表中的一个或多个行相关,但第二个表中的一个行只可以与第一个表中的一个行相关。

1.2.2 创建实体类

public class Student {
  private Integer sId;
  private String sName;
  private Long sAge;
  private String sSex;
  private Integer cId;

	// set and get
}
public class Class {
  private Integer cId;
  private String cName;
  private String cAddr;
  private List<Student> students;

	// set and get
}

1.1.3 创建 DAO 接口

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description DAO 接口
 */
public interface ClassDao {
  public List<Class> findAll();
}

1.1.4 配置 mapper

<?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.software.mybatis.dao.ClassDao">
  <resultMap id="resMap" type="Class">
    <result property="cId" column="c_id"/>
    <result property="cName" column="c_name"/>
    <result property="cAddr" column="c_addr"/>
    <collection property="students" ofType="Student">
      <result property="sId" column="s_id" />
      <result property="sName" column="s_name"/>
      <result property="sAge" column="s_age"/>
      <result property="sSex" column="s_sex"/>
      <result property="cId" column="c_id"/>
    </collection>
  </resultMap>
  <select id="findAll" resultMap="resMap">
    select * from student s, class c where s.c_id = c.c_id
  </select>
</mapper>

1.1.5 测试

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description 测试类
 */
public class MybatisDemo {

  @Test
  public void TestA() throws IOException {
    // 加载核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
    // 获得 sqlSession 工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    // 获得 sqlSession 对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    List<Class> list = sqlSession.selectList("com.software.mybatis.dao.ClassDao.findAll");

    for (Class aClass : list) {
      System.out.println(aClass);
    }
  }

}

1.3 多对多查询

1.3.1 概述

  多对多关系是关系数据库中两个表之间的一种关系, 该关系中第一个表中的一个行可以与第二个表中的一个或多个行相关。第二个表中的一个行也可以与第一个表中的一个或多个行相关。该关系一般会借助第三方表实现。

1.3.2 创建实体类

public class Course {
  private Integer cId;
  private String cName;
  private List<Student> students;

	// set and get
}
public class Student {
  private Integer sId;
  private String sName;
  private Long sAge;
  private String sSex;
  private List<Course> courses;

	// set and get
}

1.3.3 创建 DAO 接口

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description course DAO 接口
 */
public interface CourseDao {
  public List<Course> findAll();
}
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description student DAO 接口
 */
public interface StudentDao {
  public List<Student> findAll();
}

1.3.4 配置 mapper

☞ student-mapper.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.software.mybatis.dao.StudentDao">
  <resultMap id="resMap" type="Student">
    <result property="sId" column="s_id" />
    <result property="sName" column="s_name"/>
    <result property="sAge" column="s_age"/>
    <result property="sSex" column="s_sex"/>
    <collection property="courses" ofType="Course">
      <result property="cId" column="c_id"/>
      <result property="cName" column="c_name"/>
    </collection>
  </resultMap>
  <select id="findAll" resultMap="resMap">
    select * from course c, student s, s_c sc where c.c_id = sc.c_id and s.s_id = sc.s_id
  </select>
</mapper>

☞ course-mapper.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.software.mybatis.dao.CourseDao">
  <resultMap id="resMap" type="Course">
    <result property="cId" column="c_id"/>
    <result property="cName" column="c_name"/>
    <collection property="students" ofType="Student">
      <result property="sId" column="s_id" />
      <result property="sName" column="s_name"/>
      <result property="sAge" column="s_age"/>
      <result property="sSex" column="s_sex"/>
    </collection>
  </resultMap>
  <select id="findAll" resultMap="resMap">
    select * from course c, student s, s_c sc where c.c_id = sc.c_id and s.s_id = sc.s_id
  </select>
</mapper>

1.3.5 测试

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/3
 * @description 测试类
 */
public class MybatisDemo {

  @Test
  public void TestA() throws IOException {
    // 加载核心配置文件
    InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
    // 获得 sqlSession 工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    // 获得 sqlSession 对象
    SqlSession sqlSession = sqlSessionFactory.openSession();

    List<Course> courseList = sqlSession.selectList("com.software.mybatis.dao.CourseDao.findAll");
    List<Student> studentList = sqlSession.selectList("com.software.mybatis.dao.StudentDao.findAll");

    System.out.println("### 课程 ###");
    for (Course course : courseList) {
      System.out.println(course);
    }

    System.out.println("### 学生 ###");
    for (Student student : studentList) {
      System.out.println(student);
    }
  }
}

到此这篇关于MyBatis 多表操作的实现的文章就介绍到这了,更多相关MyBatis 多表操作内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 结合mybatis-plus实现简单不需要写sql的多表查询

    项目地址: GITHUB (本地下载) java mybatis 多表查询 简介 实现简单的实体类操作多表,  首先你的项目是使用了mybatis-plus 才可以使用 设计说明 如何关联表? 找第一张表注解为 TableId (mybatis-plus 注解)的属性名, 到每二张表找同样的属性名, 如果没找到,反过来找,如果还没找到,挨个属性找.以此类推,实现关联的前提条件是 主从表的关联例名必须一样 // user 表 @TableId private Integer userId // a

  • Mybatis批量删除多表

    一. 这里主要考虑两种参数类型:数组或者集合. 而这点区别主要体现在EmpMapper.xml文件中标签的collection属性: 当collection="array"时,表名参数为数组; 当collection="list"时,表名参数为集合. 二. 注意: 无论Mybatis是与mysql数据库结合,还是与Oracle数据库,都同样适合如下设置与操作. 三. 具体示例如下: EmpMapper.xml: <!-- 批量删除员工信息 --> <

  • Mybatis多表关联查询的实现(DEMO)

    概要 本节要实现的是多表关联查询的简单demo.场景是根据id查询某商品分类信息,并展示该分类下的商品列表. 一.Mysql测试数据 新建表Category(商品分类)和Product(商品),并插入几条测试数据. create table Category ( Id int not null auto_increment, Name varchar(80) null, constraint pk_category primary key (Id) ); INSERT INTO category

  • Mybatis基于注解实现多表查询功能

    对应的四种数据库表关系中存在四种关系:一对多,多对应,一对一,多对多.在前文中已经实现了xml配置方式实现表关系的查询,本文记录一下Mybatis怎么通过注解实现多表的查询,算是一个知识的补充. 同样的先介绍一下Demo的情况:存在两个实体类用户类和账户类,用户类可能存在多个账户,即一对多的表关系.每个账户只能属于一个用户,即一对一或者多对一关系.我们最后实现两个方法,第一个实现查询所有用户信息并同时查询出每个用户的账户信息,第二个实现查询所有的账户信息并且同时查询出其所属的用户信息. 1.项目

  • Mybatis-Plus 多表联查分页的实现代码

    上一节,简单讲述了 Mybatis-Plus 搭建与使用入门,这一节,简单讲一下如何使用 MP 实现多表分页. 分析 使用的工程,依旧是 spring-boot,关于分页,官网给出了一个单表的demo,其实多表分页实现原理相同,都是通过 mybatis 的拦截器 (拦截器做了什么?他会在你的 sql 执行之前,为你做一些事情,例如分页,我们使用了 MP 不用关心 limit,拦截器为我们拼接.我们也不用关心总条数,拦截器获取到我们 sql 后,拼接 select count(*) 为我们查询总条

  • Spring boot2基于Mybatis实现多表关联查询

    模拟业务关系: 一个用户user有对应的一个公司company,每个用户有多个账户account. spring boot 2的环境搭建见上文:spring boot 2整合mybatis 一.mysql创表和模拟数据sql CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `company_id` int(11) NOT NULL, PRI

  • MyBatis 多表操作的实现

    1.1 一对一查询 1.1.1 概述   关系数据库中第一个表中的单个行只可以与第二个表中的一个行相关,且第二个表中的一个行也只可以与第一个表中的一个行相关. 1.1.2 创建实体类 public class Student { private Integer id; private String name; private Boolean age; private String sex; private StudentStatus studentStatus; // set and get }

  • MyBatis多表操作查询功能

    一对一查询 用户表和订单表的关系为,一个用户多个订单,一个订单只从属一个用户 一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户 在只查询order表的时候,也要查询user表,所以需要将所有数据全部查出进行封装SELECT *,o.id oid FROM orders o,USER u WHERE o.uid=u.id 创建Order和User实体 order public class Order { private int id; private Date ordertime;

  • Mybatis示例讲解注解开发中的单表操作

    目录 Mybatis注解开发单表操作 MyBatis的常用注解 MyBatis的增删改查 注解开发总结 常用注解 配置映射关系 练习项目代码 Mybatis注解开发单表操作 MyBatis的常用注解 Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了.我们先围绕一些基本的CRUD来学习,再学习复杂映射多表操作. 注解 说明 @Insert 实现新增 @Update 实现更新 @Delete 实现删除 @Select 实现查询 @Result 实现结果集封装 @Re

  • 使用Mybatis对数据库进行单表操作的实现示例

    简介 该篇文章主要是介绍如何使用MyBatis对Mysql数据库进行单表操作(对于mybatis的下载以及配置文件的作用和具体信息,我在上一篇文章中也已经提到了),使用的环境如下: JDK版本:1.8 编译器:IDEA2019 JDBC版本:8.0.18 mybatis版本:3.5.3 配置文件 首先需要有两个配置文件,一个是configuration.xml文件,配置的是连接数据库的环境以及对于mapper.xml文件的映射,还有另一个文件就是mapper.xml,这个文件主要是用来写sql语

  • mybatis 多表关联mapper文件写法操作

    两张表SystemParam(系统参数表) Suit (主题) SystemParam 与 Suit 是多对一 Suit 的higerSuit字段是Suit 的父及主题id 是多对一,需要自连接查询,因为重名所以父表sql字段加别名 mapper方法 Systemparam selectJoinSuit(String strparamcode); Po类 public class Systemparam { //ManyToOne "主题" private Suit suitobj;

  • Mybatis注解开发单表、多表操作的实现代码

    一.Mybatis注解开发单表操作 *** 1.1 MyBatis的常用注解 之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的 而这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了 常用注解 @Select("查询的 SQL 语句"):执行查询操作注解 @Insert("查询的 SQL 语句"):执行新增操作注解 @Update("查询的 SQL 语句"):

  • Java Mybatis框架多表操作与注解开发详解分析

    目录 一对一查询 多对多查询 Mybatis的注解开发 Mybatis的增删查改 MyBatis的注解实现复杂映射开发 一对一查询 一对一查询的模型 用户表和订单表的关系为,一个用户有多个订单,一个订单只从属于一个用户. 一对一查询的需求:查询一个订单,与此同时查询出该订单所属的用户 一对一查询的语句 对应的sql语句: select * from orders o,user u where o.uid=u.id;查询的结果如下: 创建Order和User实体 创建OrderMapper接口 p

  • springboot+mybatis拦截器方法实现水平分表操作

    目录 1.前言 2.MyBatis 允许使用插件来拦截的方法 3.Interceptor接口 4分表实现 4.1.大体思路 4.2.1 Mybatis如何找到我们新增的拦截服务 4.2.2 应该拦截什么样的对象 4.2.3 实现自定义拦截器 4.2.逐步实现 1.前言 业务飞速发展导致了数据规模的急速膨胀,单机数据库已经无法适应互联网业务的发展.由于MySQL采用 B+树索引,数据量超过阈值时,索引深度的增加也将使得磁盘访问的 IO 次数增加,进而导致查询性能的下降:高并发访问请求也使得集中式数

  • MyBatis中insert操作返回主键的实现方法

    在使用MyBatis做持久层时,insert语句默认是不返回记录的主键值,而是返回插入的记录条数:如果业务层需要得到记录的主键时,可以通过配置的方式来完成这个功能 针对Sequence主键而言,在执行insert sql前必须指定一个主键值给要插入的记录,如Oracle.DB2,可以采用如下配置方式: <insert id="add" parameterType="vo.Category"> <selectKey resultType="

  • Mybatis 动态表名+Map参数传递+批量操作详解

    需求: 之前项目一个变动,需要对3张mysql数据库表数据进行清洗,3张表表名不同,表结构完全相同,需要对这3张表进行相同的增.改.查动作,一开始比较紧急先对一张表进行操作,后来复制了3个一样的 service.dao.mapper等.后来对代码进行优化,研究了一下动态表名的处理. 1,查询操作: 查询操作只需要传入动态表名的时候,传递参数仍然是map mapper.xml内,需要使用statementType="STATEMENT",采用非预编译模式 mapper.xml内,动态表名

随机推荐