Hibernate中,二级缓存在Hibernate中对应的即SessionFactory范围的缓存,是进程缓存或集群缓存,二级缓存在Hibernate中是可以配置的,可以通过在hibernate.cfg.xml来如下来指定二级缓存。 1. 打开hibernate的二级缓存 <property name="cache.use_second_level_cache">true</property> 2.指定第三方二级缓存框架为EhCache <property name="cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> 3.打开查询缓存 <property name="cache.use_query_cache">true</property>
为了让学员们更好地理解各个查询方法与二级缓存的关系,我在教学过程中使用了如下的一些示例来给与说明:
先写统计分析二级缓存的方法 //测试统计分析二级缓存或查询缓存的内容 public void testSecondLevelStatistics(String regionName){ Map<Object,Object> map=HibernateSessionFactory.getSessionFactory() .getStatistics() .getSecondLevelCacheStatistics(regionName) .getEntries(); System.out.println("开始遍历键"); for(Object object: map.keySet()){ System.out.println(object); } System.out.println(); System.out.println("开始遍历值"); for(Object object: map.values()){ System.out.println(object); } }
该方法说明如下:该方法返回Map,得到缓存的键的Set,及缓存的对象的Set。然后我们在控制台下输出,以确定到底有没有缓存,以及缓存的键与值分别是什么,便于学员们更好地理解二级缓存。
先看第一个我们常用的查询方法:get
/测试get方法的二级缓存 public void testCacheByGet(){ Session session=super.getSession(); //设置session如何与二级缓存交互,默认为normal session.setCacheMode(CacheMode.GET); Fwxx fwxx=(Fwxx)session.get(Fwxx.class ,1); System.out.println("第一次输出:"+fwxx.getLxr()); super.closeSession(); System.out.println(); testSecondLevelStatistics("com.jc.mysql.entity.Fwxx"); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace(); } fwxx=(Fwxx)super.get(1,Fwxx.class); System.out.println("第二次输出:"+fwxx.getLxr()); } //测试load方法的二级缓存 public void testCacheByLoad(){ Session session=super.getSession(); session.setCacheMode(CacheMode.PUT); Fwxx fwxx=(Fwxx)session.load(Fwxx.class,1); System.out.println("第一次输出:"+fwxx.getId()); super.closeSession(); System.out.println(); testSecondLevelStatistics("com.jc.mysql.entity.Fwxx"); HibernateSessionFactory.getSessionFactory() .evict(Fwxx.class, 1); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace(); } //session=super.getSession(); //fwxx=(Fwxx)session.load(Fwxx.class,1); System.out.println("第二次输出:"+fwxx.getTel()); } |