博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot + Mybatis-plus实战之Mybatis-plus的一级缓存、二级缓存
阅读量:2352 次
发布时间:2019-05-10

本文共 4735 字,大约阅读时间需要 15 分钟。

前言

现在的JAVA行业,貌似已经是SpringBoot + SpringCloud 的天下了,早期的SSH,SSM框架已经老去,与SpringBoot相结合的JPA框架虽然省去了很多的增删改查sql,但是比较笨拙,在面对一些复杂多变的逻辑时常常力不从心,而相对应的Mybatis由于其高度的灵活性受到广大JAVA攻城狮的欢迎。之前整合过了springboot+mybatis,前几天看到一个面试的问一个问题,Mybatis的一级缓存,二级缓存。我想这个应该也是一个重点吧,所以今天决定来详细解读一下神秘的一二级缓存。

一级缓存是SqlSession级别的缓存。在操作数据库时需要构造sqlSession对象,在对象中有一个数据结构(HashMap)用于存储缓存数据。不同的sqlSession之间的缓存数据区域(HashMap)是互相不影响的。 一级缓存是默认开启的不用配置。

二级缓存是mapper级别的缓存,多个SqlSession去操作同一个Mapper的sql语句,多个SqlSession可以共用二级缓存,二级缓存是跨SqlSession的。二级缓存的开启(实体类必须序列化),然后在配置文件里面配置。
MyBatis-plus 配置要点
核心要点1

mybatis-plus 在springboot 中的核心配置如下

1

2
3
4
mybatis-plus.configuration.cache-enabled=true
mybatis-plus.mapper-locations=classpath*:/mapper/*.xml
mybatis-plus.type-aliases-package=com.sch.app.mybatis.entity
logging.level.com.sch.app.mybatis.mapper= debug
所需依赖 除了基本的springboot依赖外,还有

核心要点2

1

2
3
4
5
6
7
8
9
10
11
12
13
<dependency>
          <groupId>com.baomidou</groupId>
          <artifactId>mybatis-plus-boot-starter</artifactId>
          <version>3.3.2</version>
        </dependency>     
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
            <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
核心要点3

mybatis 语句生成 generatorConfig.xml 用它一步生成需要的基本实体类和接口以及mapper文件(resouses目录下)

1

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
  <!-- <properties resource="mybatis.properties" />
     -->
  <classPathEntry location="D:\AJava\mysql-connector-java-8.0.16.jar" />
  <context id="msqlTables" targetRuntime="MyBatis3">
    <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
    <jdbcConnection connectionURL="jdbc:mysql://localhost:3306/alexshi?serverTimezone=GMT%2B8"
            driverClass="com.mysql.cj.jdbc.Driver" password="1234" userId="root" >
 
      <property name="nullCatalogMeansCurrent" value="true"/>
    </jdbcConnection>
    <javaTypeResolver>
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <javaModelGenerator targetPackage="com.sch.app.mybatis.entity" targetProject="SpringbootMybatis\src\main\java">
      <property name="enableSubPackages" value="true"/>
      <!-- 从数据库返回的值被清理前后的空格 -->
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <sqlMapGenerator targetPackage="mapper" targetProject="SpringbootMybatis\src\main\resources">
      <property name="enableSubPackages" value="true"/>
    </sqlMapGenerator>
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.sch.app.mybatis.mapper" targetProject="SpringbootMybatis\src\main\java">
      <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>
 
    <!--数据库表-->
    <table schema="" tableName="d_dictionary"></table>
    <table schema="" tableName="d_dictionary_type"></table>
    <table schema="" tableName="c_resource"></table>
    <table schema="" tableName="c_role"></table>
    <table schema="" tableName="c_role_resource"></table>
    <table schema="" tableName="c_user_online"></table>
    <table schema="" tableName="c_user"></table>
    <table schema="" tableName="c_user_role"></table>
    <table schema="" tableName="test"></table>
  </context>
</generatorConfiguration>
在这里插入图片描述

这个 Run Mybatis Generator 可以在eclipse 的插件市场下的

点击执行后生成以下内容

在这里插入图片描述

在这里插入图片描述

Mybatis-plus 一级缓存的测试

首先一定要开启日志 方便查看效果

1

logging.level.com.sch.app.mybatis.mapper= debug
com.sch.app.mybatis.mapper 也就是 mapper接口的目录

在这里插入图片描述

测试代码1

1

2
3
4
5
6
7
8
9
10
11
12
@Autowired
private SqlSessionFactory sqlSessionFactory;
 
 @RequestMapping(value = "/testMybatis")
 @ResponseBody
 public void testMybatis(){
     SqlSession sqlSession = sqlSessionFactory.openSession();
     TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
      for (int i = 0; i < 3; i++) {
        Test selectByPrimaryKey = testMapper.selectByPrimaryKey(5);
        log.info("结果:"+ selectByPrimaryKey.getUsername());
 }
在这里插入图片描述

结果是

在这里插入图片描述

可以看出,只搜索了一次,第二三次都没有sql打印

测试代码2

1

2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RequestMapping(value = "/testMybatis")
     @ResponseBody
     public void testMybatis(){
         SqlSession sqlSession = sqlSessionFactory.openSession();
         TestMapper testMapper = sqlSession.getMapper(TestMapper.class);
          for (int i = 0; i < 3; i++) {
            Test selectByPrimaryKey = testMapper.selectByPrimaryKey(5);
            log.info("结果:"+ selectByPrimaryKey.getUsername());
            if (i == 2) {
                selectByPrimaryKey.setUsername("刘惜君的妹妹");
                testMapper.updateByPrimaryKey(selectByPrimaryKey);
                Test selectByPrimaryKey2 = testMapper.selectByPrimaryKey(5);
                log.info("更新后的用户名:"+ selectByPrimaryKey2.getUsername());
                }
     }
打印结果:

在这里插入图片描述

可见,第一次我加入了更新的代码后再次查询的时候,就又执行了sql语句,说明当执行插入、更新、删除,会清空SqlSession中的一级缓存。只有查询的操作,一级缓存才不会被清除。

转载地址:http://ybevb.baihongyu.com/

你可能感兴趣的文章
给定一个整数sum,从有N个无序元素的数组中寻找元素a、b、c、d,使得 a+b+c+d =sum,最快的平均时间复杂度是____。
查看>>
设二叉树结点的先根序列、中根序列和后根序列中,所有叶子结点的先后顺序____。
查看>>
将整数序列(7-2-4-6-3-1-5)按所示顺序构建一棵二叉排序树a(亦称二叉搜索树),之后将整数8按照二叉排序树规则插入树a中,请问插入之后的树a中序遍历结果是____。
查看>>
IP地址、子网掩码、网络号、主机号、网络地址、主机地址
查看>>
已知int a[]={1,2,3,4,5};int*p[]={a,a+1,a+2,a+3};int **q=p;表达式*(p[0]+1)+**(q+2)的值是____。
查看>>
CPU输出数据的速度远远高于打印机的打印速度,为了解决这一矛盾,可采用()
查看>>
整型字符常量和字符字面量的区别 sizeof(char) 和 sizeof('a')
查看>>
表的主键特点中,说法不正确的是()
查看>>
用变量a给出下面的定义:一个有10个指针的数组,该指针指向一个函数,该函数有一个整形参数并返回一个整型数
查看>>
冯诺依曼工作方式的基本特点是____
查看>>
下列关于文件索引结构的叙述中,哪些是正确的?
查看>>
Java异常处理
查看>>
JQueryUI实现对话框
查看>>
Java流(Stream)/文件(File)/IO
查看>>
文件处理(压缩与解压)
查看>>
Java中的目录
查看>>
JQuery实现对select选择框的赋值
查看>>
SweetAlert插件
查看>>
JSON学习
查看>>
有关项目的基础知识
查看>>