一级缓存:
mybatis默认是开启,有效范围是同一个sqlsession对象
第一次查询完成后,结果会存到缓存中,第二次相同语句的查询,就会在缓存中找,而不走数据库查询
但是:在执行增加 删除 修改操作后会清空缓存(事务提交)
二级缓存:
需要手动开启
1,在配置文件中开启缓存(默认开启,可不管)
<setting name="cacheEnabled"value="true"/>
2,sql映射文件中,添加<cache标签
<cache eviction="FIFO"flushInterval="60000"size="512"readOnly="true"/>
3,查询对象类实现序列化接口(保证安全,查询结果序列化到缓存中)
注意点:测试二级缓存需要使用同一个sqlsessionfactory对象,单例模式可以搞一个util类
测试代码:
@Test
public void selectUserParam1() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession(true);
SqlSession sqlSession1 = sessionFactory.openSession(true);
StuMapper2 mapper = sqlSession.getMapper(StuMapper2.class);
long l = System.currentTimeMillis();
User zs = mapper.selectUserParam(2, "zs");
long l1 = System.currentTimeMillis();
System.out.println(l1-l+"毫秒");
sqlSession.close();
StuMapper2 mapper1 = sqlSession1.getMapper(StuMapper2.class);
long ll = System.currentTimeMillis();
User zsl = mapper1.selectUserParam(2, "zs");
long l1l = System.currentTimeMillis();
System.out.println(ll-l1l+"毫秒");
sqlSession1.close();
}
结果