二级缓存是mapper映射级别的缓存,多个SqlSession去操作同一个Mapper映射的sql语句,多个SqlSession可以共用二级缓存,

二级缓存是跨SqlSession的。

二级缓存结构图

首先开启mybatis的二级缓存。

sqlSession1去查询用户信息,查询到用户信息会将查询数据存储到二级缓存中。

第一步:在SqlMapConfig.xml文件开启二级缓存

    <settings><setting name="cacheEnabled" value="true"/></settings>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 配置properties--><properties resource="jdbcConfig.properties"></properties><settings><setting name="cacheEnabled" value="true"/></settings><!--使用typeAliases配置别名,它只能配置domain中类的别名 --><typeAliases><package name="com.learn.domain"></package></typeAliases><!--配置环境--><environments default="mysql"><!-- 配置mysql的环境--><environment id="mysql"><!-- 配置事务 --><transactionManager type="JDBC"></transactionManager><!--配置连接池--><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></dataSource></environment></environments><!-- 配置映射文件的位置 --><mappers><package name="com.learn.dao"></package></mappers>
</configuration>

第二步:配置相关的Mapper映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learn.dao.IUserDao"><!-- 开启user支持二级缓存 --><cache/><!-- 查询所有 --><select id="findAll" resultType="user">select * from user</select><!-- 根据id查询用户 --><select id="findById" parameterType="INT" resultType="user" useCache="true">select * from user where id = #{uid}</select><!-- 更新用户信息--><update id="updateUser" parameterType="user">update user set username=#{username},address=#{address} where id=#{id}</update>
</mapper>

第三步:配置statement上面的useCache属性

    <select id="findById" parameterType="INT" resultType="user" useCache="true">select * from user where id = #{uid}</select>

二级缓存测试

package com.learn.test;import com.learn.dao.IUserDao;
import com.learn.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;import java.io.InputStream;/*** @author 黑马程序员* @Company http://www.ithiema.com*/
public class SecondLevelCacheTest {private InputStream in;private  SqlSessionFactory factory;@Before//用于在测试方法执行之前执行public void init()throws Exception{//1.读取配置文件,生成字节输入流in = Resources.getResourceAsStream("SqlMapConfig.xml");//2.获取SqlSessionFactoryfactory = new SqlSessionFactoryBuilder().build(in);}@After//用于在测试方法执行之后执行public void destroy()throws Exception{in.close();}/*** 测试一级缓存*/@Testpublic void testFirstLevelCache(){SqlSession sqlSession1 = factory.openSession();IUserDao dao1 = sqlSession1.getMapper(IUserDao.class);User user1 = dao1.findById(41);System.out.println(user1);sqlSession1.close();//一级缓存消失SqlSession sqlSession2 = factory.openSession();IUserDao dao2 = sqlSession2.getMapper(IUserDao.class);User user2 = dao2.findById(41);System.out.println(user2);sqlSession2.close();System.out.println(user1 == user2);}}

经过上面的测试,我们发现执行了两次查询,并且在执行第一次查询后,我们关闭了一级缓存,再去执行第二次查询时,

我们发现并没有对数据库发出sql语句,所以此时的数据就只能是来自于我们所说的二级缓存。

二级缓存注意事项

当我们在使用二级缓存时,所缓存的类一定要实现java.io.Serializable接口,这种就可以使用序列化方式来保存对象。

package com.learn.domain;import java.io.Serializable;
import java.util.Date;public class User implements Serializable {private Integer id;private String username;private String address;private String sex;private Date birthday;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}//    @Override
//    public String toString() {
//        return "User{" +
//                "id=" + id +
//                ", username='" + username + '\'' +
//                ", address='" + address + '\'' +
//                ", sex='" + sex + '\'' +
//                ", birthday=" + birthday +
//                '}';
//    }
}

mybatis的二级缓存相关推荐

  1. Mybatis集成二级缓存与同时使用缓存与事务存在的坑

    今天在看分布式事务的时候,突然收到app不能签到的消息,赶紧解决. 具体解决方法: 1.把执行错误的处理方法提取出来,作为测试方法 2.这个方法里面有两个插入语句,一条查询语句,一个更新语句,涉及到三 ...

  2. Java Web现代化开发:Spring Boot + Mybatis + Redis二级缓存

    背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybatis是一个十分轻量好用的ORM框架.Redis是当今十分主流的分布式key- ...

  3. 【MyBatis笔记12】MyBatis中二级缓存相关配置内容

    这篇文章,主要介绍MyBatis中二级缓存相关配置信息. 目录 一.MyBatis二级缓存 1.1.cache标签相关属性 (1)eviction属性 (2)size属性 (3)flushIntern ...

  4. Springboot 集成 mybatis 开启二级缓存(redis)

    首先来了解下mybatis 缓存,mybatis缓存分为一级缓存和二级缓存.一级缓存是默认开启的,无需其他配置操作,二级缓存则需要手动设置开启. 一级缓存原理: Mybatis的一级缓存是指同一个Sq ...

  5. Mybatis实现二级缓存

    目录 一.Mybatis实现Ehcache作为二级缓存 1.导入相关依赖 2 .修改日志配置,因为ehcache使用了Slf4j作为日志输出 3. 在Resource中添加一个ehcache.xml的 ...

  6. mysql二级缓存redis_SpringBoot+Mybatis+redis(二级缓存)搭建

    刚刚开始接触Spring Boot,因为极简单的配置开发,搭建一个通用的Spring Boot+Mybaitis+redis的开发框架. 一.用maven构建项目,pom.xml文件如下: org.s ...

  7. Mybatis之二级缓存简析

    2019独角兽企业重金招聘Python工程师标准>>> 注:Mybatis的版本是3.5.0. 上一篇分析了一级缓存,这篇来分析二级缓存. 以下的内容,跳过了很多细节,可以去看这篇博 ...

  8. mybatis开启二级缓存和懒加载,类型别名,类都简称

    SqlMapConfig.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE conf ...

  9. Mybatis 之 二级缓存

    1.二级缓存 二级缓存的原理和一级缓存原理一样,第一次查询,会将数据放入缓存中,然后第二次查询则会直接去缓存中取.但是一级缓存是基于sqlSession的,而二级缓存是基于mapper文件的names ...

最新文章

  1. K-近邻算法之案例:鸢尾花种类预测--数据集介绍
  2. IDEA配置maven报错解决方案
  3. 软工三(5.12上课)
  4. c++ 私有内部类_Java内部类新解,你没有见过的船新版本
  5. 20145319 第五周学习总结
  6. SpringCloud 超详细个人笔记
  7. 绝对定位relative、相对定位absolute(脱离文档流)
  8. 二十六岁,裸辞之后,我步入了“三无”行列
  9. 递归--练习6--noi1755菲波那契数列
  10. 【BZOJ】3143: [Hnoi2013]游走
  11. CSDN下载码如何使用?
  12. solidworks——铝型材画法
  13. android 获取机顶盒ip,在电视机顶盒端查看IP地址 - 零成本让你的电视盒子变身无线路由器...
  14. android动画特效,安卓——之Animation动画特效
  15. 城市公交类毕业论文文献都有哪些?
  16. Linux图形终端与字符终端
  17. 二分查找边界问题总结
  18. 热力图回归Adaptive Wing Loss [ICCV2019] 论文阅读
  19. 5月第2周业务风控关注 | 等保2.0将于5月13日正式发布
  20. 乔伊·伯纳尔(Joey Bernal)的评论专栏,社交网络的三阶段路线图

热门文章

  1. MySQL纯透明的分库分表技术还没有
  2. 不需要密码的windows计划任务设置
  3. struts升级:FileUploadInterceptor在struts 2.3.14.2的jar中修改了方法acceptFile中的参数
  4. 个人Wordpress站点设置Windows Live writer
  5. httpRuntime 一点经验---引
  6. (七)webStorage使用实例——webStorage作为简易数据库来使用
  7. I/O流(三)—对象的序列化和反序列化
  8. BZOJ3028食物——生成函数+泰勒展开
  9. postgres循环sql
  10. vue从入门到进阶:自定义指令directive,插件的封装以及混合mixins(七)