二级缓存是sessionFactory级别的缓存(跨越了两个session),是需要手动开启的。
需求:操作MySQL中数据库seamybatis中的user表,使用二级缓存查询37号尤海的信息:
手动开启方式:
1:SqlMapConfig.xml配置文件中添加开启全局缓存
<settings>
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false" />
//开启全局缓存
<setting name="cacheEnabled" value="true"/>
</settings>
2:映射文件UserMapper.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.sea.crm.mapper.UserMapper">
<!-- 开启user对象查询的二级缓存 -->
<cache/>
<!-- 根据ID查询用户 -->
<select id="queryById" parameterType="int" resultType="com.sea.crm.pojo.User">
select *
from user where id = #{id}
</select>
</mapper>
单元 测试 如下:
@Test
public void testquerybyIdcache2() {
SqlSession session1 = factory.openSession();
User user1 = session1.selectOne("com.sea.crm.mapper.UserMapper.queryById", 37);
System.out.println(user1);
// 记得提交事务,否则无效
session1.commit();
SqlSession session2 = factory.openSession();
User user2 = session2.selectOne("com.sea.crm.mapper.UserMapper.queryById", 37);
System.out.println(user2);
}
效果: