- /**
- * @TODO:查詢某一年度的所有計劃數量
- */
- public int findCountByYear(String currYear) {
- String hqlString = "select count(*) from WaterPlan as p where 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函數如count(), sum()的唯一返回值已經從Integer變爲Long,如果不升級代碼,會得到一個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();