Hibernate使用count(*)取得表中記錄總數

 

Java代碼  收藏代碼
  1. /** 
  2.   * @TODO:查詢某一年度的所有計劃數量 
  3.   */  
  4. public int findCountByYear(String currYear) {  
  5.     String hqlString = "select count(*) from WaterPlan as p where p.planYear ='"+currYear+"'";  
  6.     Query query = this.getSession().createQuery(hqlString);  
  7.           
  8.     return ((Number)query.uniqueResult()).uniqueResult();  
  9. }  

 從Hibernate 3.0.x/3.1.x升級到最新的3.2版之後,3.2版的很多sql函數如count(), sum()的唯一返回值已經從Integer變爲Long,如果不升級代碼,會得到一個ClassCastException。 

這個變化主要是爲了兼容JPA,可以在hibernate.org的最新文檔中找到說明。 

Hibernate Team也提供了一個與原來兼容的解決方案:

Java代碼  收藏代碼
  1. Configuration classicCfg = new Configuration();   
  2. classicCfg.addSqlFunction( "count"new ClassicCountFunction());   
  3. classicCfg.addSqlFunction( "avg"new ClassicAvgFunction());   
  4. classicCfg.addSqlFunction( "sum"new ClassicSumFunction());   
  5. SessionFactory classicSf = classicCfg.buildSessionFactory();   

 
或 

Java代碼  收藏代碼
  1. //int count = ((Integer)query.uniqueResult()).intValue();   
  2. //改成   
  3.   
  4. int count = ((Number)query.uniqueResult()).intValue();   
  5.   
  6. //這樣就可以兩個版本同時兼容.   

  

Java代碼  收藏代碼
  1. //參考代碼  
  2. //第一種方法:  
  3.   String hql = "select count(*) from User as user";  
  4.   Integer count = (Integer)getHibernateTemplate().find(hql).listIterator().next();  
  5.   return count.intValue();  
  6.   
  7. //第二種方法:  
  8.  String hql = "select count(*) from User as user";  
  9.   return ((Integer)getHibernateTemplate().iterate(hql).next()).intValue();  
  10.   
  11. //第三種方法:  
  12.  String hql = "select count(*) from User as user";  
  13.  Query query =  getHibernateTemplate().createQuery( getSession(),hql);  
  14.  return ((Integer)query.uniqueResult()).intValue();  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章