接连载1,在连载1的最后,我编写了 public void testCacheByGet()与public void testCacheByLoad()方法,主要想讲解什么问题呢?就是向学员们说明在原有理解一级缓存的基础上(一级缓存主要完成持久化管理与服务),而这里我们所讲解的二级缓存,除了一些特殊的要求之外,二级缓存可以大幅度地提高应用系统的性能。当然这两个方法在演示二级缓存的时候,基本的效果是一样的。Get()与load()方法的细微的区别,这里,我就不多说了。
想要掌握Hibernate,点击详细了解
下面再来看一下一对多情况下的集合级的缓存 代码如下:其中Fwlx(房屋类型)与Fwxx(房屋信息)是一对多的关系,我的目的是测试多方的集合的缓存情况,方便学员们进一步理解。 //测试get方法的Collection二级缓存 public void testCacheByGetCollection(){ Fwlx fwlx=(Fwlx)super.get(2,Fwlx.class); System.out.println("第一次输出:"+fwlx.getId()); super.closeSession(); System.out.println("--------------------------------"); testSecondLevelStatistics("com.jc.mysql.entity.Fwlx"); testSecondLevelStatistics("com.jc.mysql.entity.Fwlx.fwxxes"); System.out.println("--------------------------------"); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace(); } fwlx=(Fwlx)super.get(2,Fwlx.class); Set<Fwxx> set=fwlx.getFwxxes(); for(Fwxx fwxx:set){ System.out.println("第二次输出:"+fwxx.getLxr()); } }
在如上代码中特别需要注意的是:红色的标注的代码。集合级别的如何做为参数。当然以上方法在对应的对象关系配置文件中需要进行的配置,这里我就不写了,请参考相关书籍。(以下其他的方法需要的配置也做同样的省略)
再来看关于Query.list()方法的测试: //测试通过query.list二级缓存及查询缓存 public void testQueryCacheByList(){ String hql="select fwxx from Fwxx fwxx"; Query query=super.getSession() .createQuery(hql); // query.setCacheable(true); // query.setCacheRegion("myQueryCache"); long beginTime=System.currentTimeMillis(); List<Fwxx> list=query.list(); for(Fwxx fwxx:list){ System.out.print("第一次输出:"+fwxx.getLxr()); } super.closeSession(); System.out.println("--------------------------------"); testSecondLevelStatistics("com.jc.mysql.entity.Fwxx"); System.out.println("--------------------------------"); try { Thread.sleep(5000); } catch (InterruptedException e){ e.printStackTrace(); } query=super.getSession().createQuery(hql); // query.setCacheable(true); list=query.list(); for(Fwxx fwxx:list){ System.out.print("第二次输出:"+fwxx.getLxr()); } long endTime=System.currentTimeMillis(); System.out.println((endTime-beginTime)/1000); }
|