一級緩存
會話級緩存,SqlSession 級別,默認是開啓
清除一級緩存對象
commit();
session.clearCache();
@Test
public void query() {
BookMapper bm = session.getMapper(BookMapper.class);
System.out.println(bm.queryAll());
System.out.println(bm.queryAll());//一級緩存
session.commit();
System.out.println(bm.queryById(3));
//session.clearCache();
System.out.println(bm.queryById(3));//一級緩存
//session.commit();
System.out.println(bm.queryById(3));
System.out.println(bm.queryById(3));
}
二級緩存
SqlSessionFactory級別緩存,會話工廠級別
SqlSession s1 = sf.openSession();
SqlSession s2 = sf.openSession();
SqlSession s3 = sf.openSession();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
開發者必須自己配置二級緩存
二級緩存是人工開啓的,需要在XxxxMapper.xml 文件中加入如下開啓
方法一
<cache eviction="FIFO" flushInterval="60000" size="5120" readOnly="true" />
<select id="queryAll" resultType="book" useCache="false"> 默認使用緩存,填寫false此操作不讓緩存
select * from book
</select>
方法二
@CacheNamespace(eviction = FifoCache.class, flushInterval = 60000, size = 1024, readWrite = true)
public interface BookMapper {
@Select("select * from book") @Options(useCache = true)
public List<Book> queryAll();
@Select("select * from book where id = #{id}")
public Book queryById(int id);
}
注意:使用緩存時,最好給實體類序列化。
java是什麼是序列化?會什麼不序列化?
測試代碼爲:
@Test
public void ccc() throws IOException, ClassNotFoundException {
SqlSession s1 = sf.openSession();
SqlSession s3 = sf.openSession();
//一級緩存
//BookMapper bm1 = s1.getMapper(BookMapper.class);
//BookMapper bm2 = s1.getMapper(BookMapper.class);
//System.out.println(bm1.queryAll());
//System.out.println(bm2.queryAll());
//二級緩存
BookMapper bm1 = s1.getMapper(BookMapper.class);
//bm1.queryById(3);
System.out.println(bm1.queryAll());
s1.commit();//二級緩存才生效
//sf.getConfiguration().getCaches().clear();
//s1.getConfiguration().getCaches().clear();
sf.getConfiguration().getCaches().clear();;
SqlSession s2 = sf.openSession();
BookMapper bm2 = s2.getMapper(BookMapper.class);
System.out.println(bm2.queryAll());//讀取二級緩存
//Book bk = new Book();
//bk.setId(1000);
//bk.setPrice(80);
//bk.setName("《java開發入門》");
//請把bk保存到硬盤上,首先確認bk實現序列化接口
//ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:/a.dat"));
//oos.writeObject(bk);
//oos.close();
//反序列化
//ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:/a.dat"));
//Book bk = (Book)ois.readObject();
//System.out.println(bk);
//System.out.println(bk.getName());
}