hibernate 简单笔记(三)
hibernate提供两类缓存:
- 一级缓存是session缓存,属于事务级缓存。hibernate不提供配置操作,但能够进行主动清除;
- 二级缓存是sessionFactory缓存,相当于把经常操作的数据缓存在内存中。之前的项目中利用了memcache和spring的AOP主动实现的,hibernate中也提供了这样的默认机制。见下面这个例子:
一.配置hibernate.cfg.xml:
<property name="cache.use_second_level_cache">true</property> <property name="cache.use_query_cache">true</property> <property name="cache.provider_class">org.hibernate.cache.OSCacheProvider</property> <property name="generate_statistics">true</property> <mapping resource="com/TBook.hbm.xml" /> <mapping resource="com/TOwner.hbm.xml" /> <class-cache usage="read-only" class="com.TOwner"/> //对TOwner的操作将使用二级缓存,缓存类型为只读
二.操作:
public static void queryTest(){ Configuration con = new Configuration(); con.configure(); SessionFactory sessionfactory = con.buildSessionFactory(); Session session = null; Transaction tran = null; for(int i = 0; i < 10; i++){ try{ session = sessionfactory.openSession(); tran= session.beginTransaction(); TOwner owner = (TOwner) session.get(TOwner.class, new Integer(1)); tran.commit(); }catch(RuntimeException e){ if(null != tran){tran.rollback();} }finally{ session.close(); } } Statistics stat = (Statistics) sessionfactory.getStatistics(); System.out.println("hit:"+stat.getSecondLevelCacheHitCount()); //显示为hit:9 System.out.println("put:"+stat.getSecondLevelCachePutCount()); //显示为put:1 System.out.println("miss:"+stat.getSecondLevelCacheMissCount());//显示为miss:1 } }
如上例可知,第一次操作get的时候缓存命中失败,因此put入缓存,之后的操作全部是查找缓存中的数据。