Mybatis入门笔记(15)——Mybatis 基于注解开发的缓存配置
-
在SqlMapconfig.xml中开启二级缓存支持
Mybatis默认开启了二级缓存,可以不用配置。
Mybatis官网: http://www.mybatis.org/mybatis-3/zh/configuration.html#settings
<!--配置二级缓存--> <settings> <!-- 开启二级缓存支持--> <setting name="cacheEnabled" value="true"/> </settings>
-
在持久层接口中使用注解配置二级缓存
/** * @ClassName: IUserDao * @author: benjamin * @createTime: 2019/07/19/21:50 */ @CacheNamespace(blocking = true) //mybatis 基于注解方式实现配置二级缓存 public interface IUserDao {
-
编写测试类
/** * @ClassName: SecondCacheTest * @author: benjamin * @version: 1.0 * @description: TODO * @createTime: 2019/07/19/21:45 */ public class SecondCacheTest { private InputStream in; SqlSessionFactory factory; @Before//用于在测试方法执行之前执行 public void init()throws Exception{ //1.读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.获取SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); } @After//用于在测试方法执行之后执行 public void destroy()throws Exception{ in.close(); } //测试二级缓存 @Test public void testFindById(){ SqlSession sqlSession = factory.openSession(true); IUserDao userDao = sqlSession.getMapper(IUserDao.class); User user = userDao.findUserById(48); System.out.println(user); sqlSession.close();//释放一级缓存 SqlSession sqlSession1 = factory.openSession(true); IUserDao userDao1 = sqlSession1.getMapper(IUserDao.class); User user1 = userDao1.findUserById(48); System.out.println(user1); sqlSession.close();//释放一级缓存 } }
开启二级缓存后,数据库只进行了一次查询。