一级缓存
会话级
同一个SqlSession接口对象调用相同的select 语句,则直接会从缓存中返回结果,而不是再查询一次数据库
mybatis 默认情况下,启用一级缓存
测试代码
public void one2many(){
//List<Book> list = bdao.queryAll();
//System.out.println("--------------------------");
Book book = bdao.queryById(2);
System.out.println(book.getName());
this.ss.clearCache(); //清除一级缓存
Book b = bdao.queryById(2);
System.out.println(book==b);
System.out.println(b.getName());
System.out.println(b.getPrice());
}
二级缓存
工厂级 全局的,开发者必须自己配置二级缓存
二级缓存是人工开启的,需要在XxxxMapper.xml 文件中加入如下开启
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />
src/main/java/com/fz/mapper/BookMapper.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.fz.mapper.BookMapper">
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />
<resultMap id="book" type="book">
<id column="book_id" property="id"/>
<result column="book_name" property="name"/>
<result column="book_price" property="price"/>
</resultMap>
<select id="queryAll" resultMap="book">
select * from book
</select>
<select id="queryById" resultMap="book">
select * from book where book_id = #{id}
</select>
</mapper>
测试代码:
@Test
public void c2(){
SqlSession s1 = this.sf.openSession();
SqlSession s2 = this.sf.openSession();
List<Book> bks = s1.getMapper(BookMapper.class).queryAll();
s1.commit(); //缓存生效
List<Book> b2k = s2.getMapper(BookMapper.class).queryAll();
Book book = s2.getMapper(BookMapper.class).queryById(2);
Book b2 = s2.getMapper(BookMapper.class).queryById(2);
//System.out.println(s1==s2);
//s1.getMapper(BookMapper.class).queryAll();
//s1.commit();
//Book b1 = s1.getMapper(BookMapper.class).queryById(2);
//s1.commit(); //会话一,事务提交缓存生效
//会话二再查询时就读取了一级缓存
//Book b2 = s2.getMapper(BookMapper.class).queryById(2);
}