hibernate 查询有关的API的不同查询方法对二级缓存及查询缓存都有着不同的支持。现在我们接着看如下的代码:
接连载2,
hibernate 查询有关的API的不同查询方法对二级缓存及查询缓存都有着不同的支持。现在我们接着看如下的代码:
//测试通过query.iterator查询使用二级缓存及查询缓存(需要在配置文件配置并取消下面的注释) public void testQueryCacheByIterator(){ String hql="from Fwxx fwxx"; Query query=super.getSession() .createQuery(hql); //query.setCacheable(true); long beginTime=System.currentTimeMillis(); Iterator it=query.iterate(); while(it.hasNext()){ Fwxx fwxx=(Fwxx)it.next(); 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(); } query=super.getSession().createQuery(hql); //query.setCacheable(true); it=query.iterate(); while(it.hasNext()){ Fwxx fwxx=(Fwxx)it.next(); System.out.println("第二次输出:"+fwxx.getLxr()); } long endTime=System.currentTimeMillis(); System.out.println((endTime-beginTime)/1000); }
与上个练习public void testQueryCacheByList()方法不同的是:Query.list查询对于二级缓存是只写不读。而Query.iterator()却即读又写。不过读者可从控制台下的生成的语句下看出,Query.iterator()方法只查询id。下面的这个方法是他们两个方法的联合使用,却最能说明问题。方法如下:
//测试通过query.list,iterator查询缓存 public void testCacheByListIterator(){ String hql="from Fwxx fwxx"; Query query=super.getSession() .createQuery(hql); long beginTime=System.currentTimeMillis(); List<Fwxx> list=query.list(); for(Fwxx fwxx:list){ // 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(); } query=super.getSession().createQuery(hql); Iterator it=query.iterate(); while(it.hasNext()){ Fwxx fwxx=(Fwxx)it.next(); // System.out.println("第二次输出:"+fwxx.getLxr()); } long endTime=System.currentTimeMillis(); System.out.println((endTime-beginTime)/1000); } 在这个方法中充分体现了作者的思维,由Query.list()完成写入缓存,由Query.iterator()方法应用缓存,从缓存中读取,大大提高查询速度。 由于Hibernate对jdbc的轻型封装,导致查询效率自然不比原生态的jdbc,不过hibernate功能强大的一级缓存,特别是对于项目开发中大量查询应用的二级缓存中的合理使用,是使我们提高项目查询效率的关键,一定要使用好,掌握透彻相关方法,否则会得不到好的效果,事倍功半。
|