学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy
你只有走完必须走的路,才能过想过的生活
测试代码
@Test
public void queryById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
String id = "0a547141ea664a438268c8f20e5dd049";
Blog blog = mapper.queryById(id);
System.out.println(blog);
System.out.println("===================================");
Blog blog1 = mapper.queryById(id);
System.out.println(blog1);
System.out.println(blog.equals(blog1));
sqlSession.close();
}
日志

查询不同

增删改操作后,可能会改变原来的数据,必定会刷新缓存

查询不同的Mapper.xml
手动清理缓存
sqlSession.clearCache(); // 手动清理缓存
小结
| 设置名 | 描述 | 有效值 | 默认值 |
|---|---|---|---|
| cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true、false | true |
<setting name="cacheEnabled" value="true"/>
<cache/>
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
测试代码
@Test
public void queryById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
String id = "0a547141ea664a438268c8f20e5dd049";
Blog blog = mapper.queryById(id);
System.out.println(blog);
sqlSession.close();
System.out.println("================关闭之后查询===================");
SqlSession sqlSession1 = MybatisUtil.getSqlSession();
BlogMapper mapper1 = sqlSession1.getMapper(BlogMapper.class);
Blog blog1 = mapper1.queryById(id);
System.out.println(blog1);
sqlSession1.close();
}

可以在单个查询语句上指定不使用二级缓存
<select id="queryById" resultType="blog" useCache="false">
select * from blog
<where>
id = #{id}
where>
select>
问题
如果没有自定义参数,则会报错,我们需要将实体类序列化!
// Cause: java.io.NotSerializableException: com.kuang.pojo.User
小结

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
maven地址
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.2.2version>
dependency>
BlogMapper.xml
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU">
defaultCache>
ehcache>
测试代码
@Test
public void queryById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
String id = "0a547141ea664a438268c8f20e5dd049";
Blog blog = mapper.queryById(id);
System.out.println(blog);
sqlSession.close();
System.out.println("================关闭之后查询===================");
SqlSession sqlSession1 = MybatisUtil.getSqlSession();
BlogMapper mapper1 = sqlSession1.getMapper(BlogMapper.class);
Blog blog1 = mapper1.queryById(id);
System.out.println(blog1);
sqlSession1.close();
}
日志没有区别
