SpringBoot使用Mybatis进行联表查询、二级缓存、三层以上嵌套

一般方式联表查询

1、t_user表

CREATE TABLE `t_user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `user_password` varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `sex` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '0' COMMENT '0是男,1是女',
  `birthday` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

2、hobby表

CREATE TABLE `hobby` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `hobby` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `belong` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `user_id` bigint DEFAULT NULL,
  `user_name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

3、主(父)实体类

@Data
public class User {
    private Long id;
    private String userName;
    private String userPassword;
    private String sex;
    private Date birthday;
    private List<Hobby> userHobby;
}

4、副(子)实体类

@Data
public class Hobby {
    private Long id;
    private String hobby;
    private String belong;
    private Long userId;
    private String userName;
}

5、主(父)mapper接口

public interface UserMapper {
    List<User> select2(Long id);
}

6、副(子)mapper接口

public interface HobbyMapper {
    Hobby select(Long userId);
}

7、主(父)mapper.xml

<mapper namespace="cn.fu.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="cn.fu.entity.User">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="user_password" jdbcType="VARCHAR" property="userPassword" />
    <result column="sex" jdbcType="CHAR" property="sex" />
    <result column="birthday" jdbcType="DATE" property="birthday" />
  </resultMap>

  <!-- 多对多关联 -->
  <resultMap id="HobbyResultMap" type="cn.fu.entity.User" extends="BaseResultMap">
    <!-- column副(子)查询参数,多个参数以column="{id=id,userName=user_name}"的形式传输,property主(父)实体类里定义的副(子)实体类名称,ofType副(子)实体类,select副(子)mapper里的查询id -->
    <collection column="id" property="userHobby" ofType="Hobby" select="cn.fu.mapper.HobbyMapper.select" fetchType="lazy"/>
  </resultMap>
  
  <sql id="Base_Column_List">
    id, user_name, user_password, sex, birthday
  </sql>
  <select id="select2" resultMap="HobbyResultMap">
    select
    <include refid="Base_Column_List" />
    from t_user
    where 1=1
    <if test="id != null">
      and id = #{id,jdbcType=BIGINT}
    </if>
  </select>
</mapper>

8、副(子)mapper.xml

<mapper namespace="cn.fu.mapper.HobbyMapper">
  <resultMap id="BaseResultMap" type="cn.fu.entity.Hobby">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="hobby" jdbcType="VARCHAR" property="hobby" />
    <result column="belong" jdbcType="VARCHAR" property="belong" />
    <result column="user_id" jdbcType="BIGINT" property="userId" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
  </resultMap>
  <sql id="Base_Column_List">
    id, hobby, belong,user_id,user_name
  </sql>
  <select id="select" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from hobby
    where 1=1
    <if test="user_id!=null">
     and user_id = #{userId,jdbcType=BIGINT}
    </if>
  </select>
</mapper>

组合方式

在这里插入图片描述
在这里插入图片描述

多对一(查询多个学生对应的一个老师)

Student.java

public class Student {
    private Long id;//ID
    private String name;//学生姓名
    private Long tId;//老师ID
    //省略get/set
}

StudentVO.java

public class StudentVO extends Student {
    private Teacher teacher;//老师对象
	//省略get/set
}

Teacher.java

public class Teacher {
    private Long id;//ID
    private String name;//老师姓名
    private String className;//班级名称
    //省略get/set
}

StudentDao.java

List<StudentVO> getStudent();

StudentMapper.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.fu.mybatis_demo.dao.StudentDao">
    <!-- 多对一 -->
    <!-- 按结果嵌套处理开始(联表查询,映射简单,sql复杂) -->
    <select id="getStudent" resultMap="StudentTeacher">
        SELECT s.id s_id,s.`name` s_name,t.id t_id, t.`name` t_name,t.class_name t_class_name  FROM student s,teacher t WHERE s.t_id = t.id
    </select>
    <!-- property对应实体类的变量名,column对应数据库字段名或自定义字段名 -->
    <resultMap id="StudentTeacher" type="StudentVO">
        <result property="id" column="s_id" jdbcType="INTEGER"/>
        <result property="name" column="s_name" jdbcType="VARCHAR"/>
        <result property="tId" column="t_id" jdbcType="VARCHAR"/>
        <association property="teacher" javaType="Teacher">
            <result property="id" column="t_id"/>
            <result property="name" column="t_name"/>
            <result property="className" column="t_class_name"/>
        </association>
    </resultMap>
    <!-- 按结果嵌套处理结束 -->
</mapper>

在这里插入图片描述

一对多(查询一个老师对应多个学生)

Teacher.java(和上面Teacher.java是同一个)

public class Teacher {
    private Long id;//ID
    private String name;//老师姓名
    private String className;//班级名称
    //省略get/set
}

TeacherVO.java

public class TeacherVO extends Teacher {
    private List<Student> students;
	//省略get/set
}

Student.java(和上面Student.java是同一个)

public class Student {
    private Long id;//ID
    private String name;//学生姓名
    private Long tId;//老师ID
    //省略get/set
}

TeacherDao.java(建议不管多少个参数都要写@Param注解和名称)

TeacherVO getTeacher(@Param("tid") Long tid);

TeacherMapper.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.fu.mybatis_demo.dao.TeacherDao">
    <!-- 一对多 -->
    <!-- 按结果嵌套 推荐联表查询 映射简单 sql复杂 -->
    <select id="getTeacher" resultMap="TeacherStudent">
        SELECT s.id s_id,s.`name` s_name,t.id t_id,t.`name` t_name,t.class_name t_class_name  FROM student s,teacher t WHERE s.t_id = t.id and t.id = #{tid}
    </select>
    <resultMap id="TeacherStudent" type="TeacherVO">
        <result property="id" column="t_id" jdbcType="INTEGER"/>
        <result property="name" column="t_name" jdbcType="VARCHAR"/>
        <result property="className" column="t_class_name" jdbcType="VARCHAR"/>
        <!-- 复杂属性,单独处理 对象:association javaType=属性类型 ;集合:collection ofType=集合泛型信息 -->
        <collection property="students" ofType="Student">
            <result property="id" column="s_id"/>
            <result property="name" column="s_name"/>
            <result property="tId" column="t_id"/>
        </collection>
    </resultMap>
</mapper>

标签的使用
下面方式等价于where 1=1 and a=a and b=b or c=c
where if动态拼接多条件,再也不用写where 1=1了!!!并且多写了个and也不怕!!!

		<where>
            <if test="id != null">
            <!-- 这里多写了个and也不会影响的,mybatis会自动帮我们去掉 -->
                and id = #{id}
            </if>
            <if test="name != null">
                and `name` = #{name}
            </if>
            <if test="className != null">
                or calss_name = #{className}
            </if>
        </where>

二级缓存(不建议使用)

mybatis:
一级缓存是默认开启的,一级缓存仅对一个会话中的数据进行缓存,离开会话就会被清除。
二级缓存是默认关闭的,二级缓存会这个会话中的数据存到内存里面并且不会清除,二级缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。

使用MyBatis二级缓存有一个前提:必须保证所有的增删改查都在同一个命名空间下才行,如果不在同一个namespace下,联表查询有可能会读出脏数据。
官网描述:
在任意一个mapper.xml的SQL 映射文件文件中加入< cache/>标签即可开启二级缓存

<cache/>

基本上就是这样。这个简单语句的效果如下:
映射语句文件中的所有 select 语句的结果将会被缓存。
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
提示: 缓存只作用于 cache 标签所在的映射文件中的语句。如果你混合使用 Java API 和 XML 映射文件,在共用接口中的语句将不会被默认缓存。你需要使用 @CacheNamespaceRef 注解指定缓存作用域。

<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>

这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512
个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

可用的清除策略有:

LRU – 最近最少使用:移除最长时间不被使用的对象。 FIFO – 先进先出:按对象进入缓存的顺序来移除它们。 SOFT –
软引用:基于垃圾回收器状态和软引用规则移除对象。 WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。 默认的清除策略是
LRU。

flushInterval(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。
默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。

size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。

readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。
因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。
速度上会慢一些,但是更安全,因此默认值是 false。

提示 :二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的
insert/delete/update 语句时,缓存会获得更新。

例子:
1、开启二级缓存配置
application.yml

mybatis:
  configuration:
    cache-enabled: true #开启二级(全局)缓存

2、需要二级缓存的实体类需要实现序列化接口
如:User.java实体类

import java.io.Serializable;

public class User implements Serializable {
	private Long id;
    private String name;
    //省略get/set
}

3、在Mapper.xml开启默认配置的二级缓存< cache/>即可。
如:UserMapper.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.fu.demo.mapper.UserMapper">
<!-- 开启二级缓存,默认配置即可 -->
<cache/>
    <resultMap type="com.fu.demo.entity.User" id="BaseResultMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
    </resultMap>
    <!-- 根据ID查询 -->
    <sql id="Base_Column_List">id, name</sql>

    <select id="select" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user
        where 1=1
        <if test="id!=null">
           AND id = #{id}
        </if>
    </select>
</mapper>

小结:
1、只要开启了二级缓存,在同一个Mapper下就有效
2、所有的数据都会先存放到一级缓存中
3、只有当会话提交,或者关闭的时候,才会提交到二级缓存

3层以上嵌套通过 resultMap 处理复杂结果映射

创建表

-- ----------------------------
-- Table structure for entity_a
-- ----------------------------
DROP TABLE IF EXISTS `entity_a`;
CREATE TABLE `entity_a`  (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of entity_a
-- ----------------------------
INSERT INTO `entity_a` VALUES (1, 'Meta');

-- ----------------------------
-- Table structure for entity_b
-- ----------------------------
DROP TABLE IF EXISTS `entity_b`;
CREATE TABLE `entity_b`  (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `a_id` int UNSIGNED NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `a_id`(`a_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of entity_b
-- ----------------------------
INSERT INTO `entity_b` VALUES (1, 1, 'Metab');

-- ----------------------------
-- Table structure for entity_c
-- ----------------------------
DROP TABLE IF EXISTS `entity_c`;
CREATE TABLE `entity_c`  (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `b_id` int UNSIGNED NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `b_id`(`b_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of entity_c
-- ----------------------------
INSERT INTO `entity_c` VALUES (1, 1, 'Metac');

-- ----------------------------
-- Table structure for entity_d
-- ----------------------------
DROP TABLE IF EXISTS `entity_d`;
CREATE TABLE `entity_d`  (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `c_id` int UNSIGNED NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `c_id`(`c_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of entity_d
-- ----------------------------
INSERT INTO `entity_d` VALUES (1, 1, 'Metad');

-- ----------------------------
-- Table structure for entity_e
-- ----------------------------
DROP TABLE IF EXISTS `entity_e`;
CREATE TABLE `entity_e`  (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT,
  `d_id` int UNSIGNED NOT NULL,
  `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `d_id`(`d_id` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of entity_e
-- ----------------------------
INSERT INTO `entity_e` VALUES (1, 1, 'Metae');

EntityA

@Data
public class EntityA {
    private Integer id;
    private String name;
    private List<EntityB> bList;
}

EntityB

@Data
public class EntityB {
    private Integer id;
    private String name;
    private List<EntityC> cList;
}

EntityC

@Data
public class EntityC {
    private Integer id;
    private String name;
    private List<EntityD> dList;
}

EntityD

@Data
public class EntityD {
    private Integer id;
    private String name;
    private List<EntityE> eList;
}

EntityE

@Data
public class EntityE {
    private Integer id;
    private String name;
}

TreeLevelResultMapper.java

public interface TreeLevelResultMapper {
    List<EntityA> findTreeLevelResult();
}

TreeLevelResultMapper.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.fu.mybatisplusdemo.mapper.TreeLevelResultMapper">

    <!-- ResultMap for EntityA -->
    <resultMap id="AMap" type="com.fu.mybatisplusdemo.entity.EntityA">
        <id column="a_id" property="id"/>
        <result column="a_name" property="name"/>
        <collection property="bList" ofType="com.fu.mybatisplusdemo.entity.EntityB" resultMap="BMap"/>
    </resultMap>

    <!-- ResultMap for EntityB -->
    <resultMap id="BMap" type="com.fu.mybatisplusdemo.entity.EntityB">
        <id column="b_id" property="id"/>
        <result column="b_name" property="name"/>
        <collection property="cList" ofType="com.fu.mybatisplusdemo.entity.EntityC" resultMap="CMap"/>
    </resultMap>

    <!-- ResultMap for EntityC -->
    <resultMap id="CMap" type="com.fu.mybatisplusdemo.entity.EntityC">
        <id column="c_id" property="id"/>
        <result column="c_name" property="name"/>
        <collection property="dList" ofType="com.fu.mybatisplusdemo.entity.EntityD" resultMap="DMap"/>
    </resultMap>

    <!-- ResultMap for EntityD -->
    <resultMap id="DMap" type="com.fu.mybatisplusdemo.entity.EntityD">
        <id column="d_id" property="id"/>
        <result column="d_name" property="name"/>
        <collection property="eList" ofType="com.fu.mybatisplusdemo.entity.EntityE" resultMap="EMap"/>
    </resultMap>

    <!-- ResultMap for EntityE -->
    <resultMap id="EMap" type="com.fu.mybatisplusdemo.entity.EntityE">
        <id column="e_id" property="id"/>
        <result column="e_name" property="name"/>
    </resultMap>

    <!-- Your Select Statement -->
    <select id="findTreeLevelResult" resultMap="AMap">
        SELECT
            a.id as a_id, a.name as a_name,
            b.id as b_id, b.name as b_name,
            c.id as c_id, c.name as c_name,
            d.id as d_id, d.name as d_name,
            e.id as e_id, e.name as e_name
        FROM entity_a a
                 LEFT JOIN entity_b b ON a.id = b.a_id
                 LEFT JOIN entity_c c ON b.id = c.b_id
                 LEFT JOIN entity_d d ON c.id = d.c_id
                 LEFT JOIN entity_e e ON d.id = e.d_id
    </select>

</mapper>

TreeLevelResultController

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * MyBatis 嵌套3层以上通过编写自定义的 resultMap 处理复杂结果映射
 */
@RestController
@RequestMapping("treeLevelResult")
@RequiredArgsConstructor
public class TreeLevelResultController {
    private final TreeLevelResultMapper treeLevelResultMapper;

    @GetMapping
    public List<EntityA> treeLevelResult() {
        return treeLevelResultMapper.findTreeLevelResult();
    }

}

返回

[
  {
    "id": 1,
    "name": "Meta",
    "blist": [
      {
        "id": 1,
        "name": "Metab",
        "clist": [
          {
            "id": 1,
            "name": "Metac",
            "dlist": [
              {
                "id": 1,
                "name": "Metad",
                "elist": [
                  {
                    "id": 1,
                    "name": "Metae"
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
]

三层以上嵌套如果出现数据错误,一定是查询出来的数据有问题

如下所示,仅仅因为时间不同,导致collection有多条数据

在这里插入图片描述

正确方法,把时间也改成一致,才能让MyBatis正确的解析collection一对多

在这里插入图片描述

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值