Hibernate 统计记录总数方法汇总
生活随笔
收集整理的這篇文章主要介紹了
Hibernate 统计记录总数方法汇总
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/***?@TODO:查詢某一年度的所有計劃數(shù)量*/publicint?findCountByYear(String?currYear)?{??String?hqlString?=?"select?count(*)?from?WaterPlan?as?pwhere?p.planYear?='"+currYear+"'";??Query?query?=?this.getSession().createQuery(hqlString);??return?((Number)query.uniqueResult()).uniqueResult();??}
??從Hibernate 3.0.x/3.1.x升級到最新的3.2版之后,3.2版的很多sql函數(shù)如count(), sum()的唯一返回值已經(jīng)從Integer變?yōu)長ong,如果不升級代碼,會得到一個ClassCastException。
??這個變化主要是為了兼容JPA,可以在hibernate.org的最新文檔中找到說明。
Hibernate Team也提供了一個與原來兼容的解決方案:
???Configuration?classicCfg?=?new?Configuration();??classicCfg.addSqlFunction(?"count",?new?ClassicCountFunction());??classicCfg.addSqlFunction(?"avg",?new?ClassicAvgFunction());??classicCfg.addSqlFunction(?"sum",?new?ClassicSumFunction());??SessionFactory?classicSf?=?classicCfg.buildSessionFactory();或
???//int?count?=?((Integer)query.uniqueResult()).intValue();//改成int?count?=?((Number)query.uniqueResult()).intValue();??//這樣就可以兩個版本同時兼容.//參考代碼//第一種方法:String?hql?=?"select?count(*)?from?User?as?user";??Integer?count?=?(Integer)getHibernateTemplate().find(hql).listIterator().next();??return?count.intValue();??//第二種方法:String?hql?=?"select?count(*)?from?User?as?user";??return?((Integer)getHibernateTemplate().iterate(hql).next()).intValue();??//第三種方法:String?hql?=?"select?count(*)?from?User?as?user";??Query?query?=??getHibernateTemplate().createQuery(?getSession(),hql);??return?((Integer)query.uniqueResult()).intValue();
轉(zhuǎn)載于:https://blog.51cto.com/jiyanle/1200572
總結(jié)
以上是生活随笔為你收集整理的Hibernate 统计记录总数方法汇总的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RHEL6.3配置文件共享(5) Sam
- 下一篇: MFC检查透镜质量程序