前言
本章学习MyBatis缓存的相关知识
方法
1.概念
我们知道,MyBatis的查询语句向数据库请求数据是非常消耗时间的,对系统的性能也是有很高的要求。
缓存的作用就相当于将查询的结果保存至内存当中,当执行同样的查询的时候能够快速的从内存中获取,而非数据库!
2.MyBatis的缓存类别
1)sqlSession缓存(一级缓存)
所谓sqlSession缓存,顾名思义就是同一个sqlSession对象查询同样的数据时,采用缓存的方式进行数据的获取。
非常好的一点就是,MyBatis默认开启一级缓存,我们无需进行任何的设置。
实例:使用sqlSession缓存
我们在studentMapper.xml编写如下代码:
编写测试类进行测试:
@Test
public void testLoginUser(){
SqlSession session = null;
try {
//获取sqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlSession对象
session = sqlSessionFactory.openSession();
StudentMapper mapper = session.getMapper(StudentMapper.class);
User user = mapper.doLogin("admin", "admin");
User user1 = mapper.doLogin("admin", "admin");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
session.close();
}
}
我们发现,我调用了两次doLogin()方法,正常打印两次SQL,实际的控制台输出为:
这是为什么呢?当然是MyBatis的缓存机制!
原理:同一个 SqlSession对象调用同一个<select>时,只有第一次访问数据库,第一次之后把查询的结果缓存到SqlSession缓存区(内存)中,其实际上缓存的时statement对象。有效范围必须为一个SqlSession对象!
实例:两个SqlSession对象调用执行
@Test
public void testLoginUser(){
SqlSession session1 = null;
SqlSession session2 = null;
try {
//获取sqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlSession对象
session1 = sqlSessionFactory.openSession();
StudentMapper mapper1 = session1.getMapper(StudentMapper.class);
User user1 = mapper1.doLogin("admin", "admin");
session2 = sqlSessionFactory.openSession();
StudentMapper mapper2 = session2.getMapper(StudentMapper.class);
User user2 = mapper2.doLogin("admin", "admin");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
session1.close();
session2.close();
}
}
控制台的输出结果如下:
这就进一步证明了我们之前的推断!
2)SqlSessionFactory缓存(二级缓存)
一级缓存是在同一个SqlSession对象之间进行的,有效范围为一个SqlSession对象,如果说我想要每个SqlSession对象调用同样的<select>也进行缓存,那么我们需要用到的就是二级缓存!
实例:使用二级缓存
在StudentMapper.xml中进行如下配置:
<!-- 设置二级缓存 -->
<cache readOnly="true"></cache>
测试类编写如下:
@Test
public void testLoginUser(){
SqlSession session1 = null;
SqlSession session2 = null;
try {
//获取sqlSessionFactory对象
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取sqlSession对象
session1 = sqlSessionFactory.openSession();
StudentMapper mapper1 = session1.getMapper(StudentMapper.class);
User user1 = mapper1.doLogin("admin", "admin");
session1.close();
session2 = sqlSessionFactory.openSession();
StudentMapper mapper2 = session2.getMapper(StudentMapper.class);
User user2 = mapper2.doLogin("admin", "admin");
session2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
控制台输出如下:
总结
缓存机制极大的提高了程序的性能!