一、配置二級緩存
1. 在mybatis_config.xml中進行如下配置:
<setting name="cacheEnabled" value="true"/>
其實這里的二級緩存默認是出於開啟狀態,因此這個位置可以不進行配置,知道有這么回事兒即可。
2.MyBatis二級緩存是和命名空間是綁定的 ,即二級緩存需要配置在 Mapper.xml 映射文件中,或者配置在 Mapper.java 接口中。在映射文件中命名空間就是 XML 根節點 mapper namespace 屬性 Mapper 接口中,命名空間就是接口的全限定名稱。
(1)在RoleMapper.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.example.simple.mapper.RoleMapper"> <cache eviction="FIFO" flushInterval="6000" size="512" readOnly="false"/> /mapper>
(2)在RoleMapper.java類中添加注解:
@CacheNamespaceRef(RoleMapper.class) public interface RoleMapper { //代碼 }
最基本的二級緩存就配置好了。
二、使用二級緩存
上面的配置是可讀寫的緩存,而 MyBatis使用 SerializedCache序列化緩存來實現可讀寫緩存類,井通過序列化和反序列化來保證通過緩存獲取數據時,得到的是一個新的實例。因此,如果配置為只讀緩存,Mybatis就會使用 Map 來存儲緩存值,這種情況下 ,從緩存中獲取的對象就是同一個實例。
public class SysRole implements Serializable { private static final long serialVersionUID = 6320941908222932112L ; /* * 其他方法 * */ }
2. 編寫測試方法如下:
@Test public void testCache2(){ SqlSession sqlSession = getSqlSession(); SysRole role = null; try{ RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); role = roleMapper.selectById(1l); role.setRoleName("new name"); SysRole role1 = roleMapper.selectById(1l); Assert.assertEquals(role1.getRoleName() , "new name"); Assert.assertEquals(role,role1); }finally { sqlSession.close(); } System.out.println("開啟新一個sqlSession" ); sqlSession = getSqlSession(); try{ RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); SysRole role1 = roleMapper.selectById(1l); Assert.assertEquals(role1.getRoleName(),"new name"); Assert.assertNotEquals(role,role1); SysRole role2 = roleMapper.selectById(1l); Assert.assertNotEquals(role1,role2); }finally { } }
測試結果如下:
DEBUG [main] - Cache Hit Ratio [com.example.simple.mapper.RoleMapper]: 0.0
DEBUG [main] - ==> Preparing: select id, role_name,enabled,create_by,create_time from sys_role where id = ?
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <== Columns: id, role_name, enabled, create_by, create_time
TRACE [main] - <== Row: 1, 管理員, 1, 1, 2020-12-01 20:05:01
DEBUG [main] - <== Total: 1
DEBUG [main] - Cache Hit Ratio [com.example.simple.mapper.RoleMapper]: 0.0
開啟新一個sqlSession
DEBUG [main] - Cache Hit Ratio [com.example.simple.mapper.RoleMapper]: 0.3333333333333333
DEBUG [main] - Cache Hit Ratio [com.example.simple.mapper.RoleMapper]: 0.5
解析:
日志中存在好幾條以 Cache Hit Ratio 開頭的語句 ,這行日志后面輸出的值為當前執行方法的緩存命中率,在測試第一部分中,第一次查詢獲取 rolel 的時候由於沒有緩存,所以執