目录
Mybatis开启二级缓存后默认使用的是内置的缓存,若需要更好的二级缓存机制,还得使用第三方专业缓存才行,以下是接入第三方缓存ehcache。
1、创建开启二级缓存的工程
2、添加依赖(pom.xml)
<!-- Mybatis EHcache整合包-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<!-- s1f4i日志门面的一个具体实现 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
3、配置缓存配置文件(ehcache.xml)
注:diskStore.path为缓存文件保存地址,按情况配置
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<!-- 磁盘保存路径 /Users/Change/Work/ehcache -->
<diskStore path="java.io.tmpdir"/>
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
日志文件配置(logback.xml)
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<!-- 指定日志输出的位置-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!--日志输出的格式 -->
<!-- 按照顺序分别是:时间、日志级别、线程名称、打印曰志的类、日志主体内容、换行 -->
<pattern>[%d{HH:mm:ss.SSS}][%-5level][%thread][%logger] [%msg]%n</pattern>
</encoder>
</appender>
<!--设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR-->
<!--指定任何一个日志级别都只打印当前级别和后面级别的曰志。-->
<root level="DEBUG">
<!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
<appender-ref ref="STDOUT" />
</root>
<!--根据特殊需求指定局部日志级别-->
<logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
</configuration>
4、配置缓存标签
<mapper namespace="org.mybatis.mapper.UserMapper">
<!-- 开始二级缓存 -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!-- 添加用户 -->
<insert id="insertUser" parameterType="User">
insert into user(name) values(#{name})
</insert>
<select id="queryUserList" resultType="User">
select * from user where name like '%小动%'
</select>
</mapper>
5、测试功能
@Test // 测试二级缓存(SessionFactory级别)
public void testTwoCache() throws IOException {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory1 = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession1 = sqlSessionFactory1.openSession(true);
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
List<User> list1 = userMapper1.queryUserList();
list1.forEach(v -> System.out.println(v.toString()));
sqlSession1.close();
SqlSession sqlSession2 = sqlSessionFactory1.openSession(true);
UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
List<User> list2 = userMapper2.queryUserList();
list2.forEach(v -> System.out.println(v.toString()));
sqlSession2.close();
}
执行结果:

306

被折叠的 条评论
为什么被折叠?



