缓存的主要作用是提高性能,可以简单的理解成一个Map;使用缓存涉及到三个操作:把数据放入缓存、从缓存中获取数据、删除缓存中的无效数据。
save,update,saveOrUpdate,load,get,list,iterate,lock这些方法都会将对象放在一级缓存中,一级缓存不能控制缓存的数量,所以要注意大批量的操作数据可能造成内存溢出;可以使用evict,clear方法清楚缓存中的内容。 但是query.list()不会从一级缓存取数据,只放不取。 session关闭后,数据就自动销毁。
一级缓存有限,需要二级缓存来弥补这个问题。 ①应用OsCache作为二级缓存 配置: 在*.hbm.xml文件中加入使用二级缓存的策略:<cache usage="read-write" /> 也可以直接在hibernate.cfg.xml中配置:<class-cache class="com.test.domain.Users" usage="read-only" /> ②Hibernate二级缓存策略: - 只读缓存(read-only) - 读写缓存(read-write) - 不严格读写缓存(nonstrict-read-write) - 事务缓存(transactional) ③统计信息打开generate_statistics,用SessionFactory.getSatistics()获取统计信息。
首先引入oscache-2.1.jar包(hibernate-distribution-3.3.1.GA\lib\optional\oscache下) ①配置hibernate.cfg.xml
<!-- 启用二级缓存 --> <property name="cache.use_second_level_cache">true</property> <!-- 指定使用哪种二级缓存 --> <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property> <!-- 产生统计信息 (这个可以不配置)--> <property name="generate_statistics">true</property> <mapping resource="com/test/domain/Student.hbm.xml" /> <mapping resource="com/test/domain/Course.hbm.xml" /> <mapping resource="com/test/domain/Studcourse.hbm.xml" /> <!-- 指定对哪个domain对象提供缓 存 --> <class-cache usage="read-write" class="com.test.domain.Student"/>②拷贝一个oscache.properties配置文件,可以使用参考文档 (\hibernate-distribution-3.3.1.GA\project\etc路径下oscache.properties文件),拷贝到src目录下。 ③统计命中信息
// 获取统计信息 Statistics ss = HibernateUtil.getSessionFactory().getStatistics(); System.out.println(ss); System.out.println("放入:" + ss.getSecondLevelCachePutCount() + "\n" + "命中:" + ss.getSecondLevelCacheHitCount()+ "\n" + "错过:" + ss.getSecondLevelCacheMissCount());