`
yinlongfei
  • 浏览: 153599 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Hibernate使用count(*)取得表中记录总数

阅读更多
String hql = ".....";
int count=((Number)hibernateSession.createQuery(hql).setLong(0, 2).setString(1, credentials.getUsername()).iterate().next()).intValue();

/** 
  * @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();  

声明:此博客从http://fengzhiyin.iteye.com/blog/376631转载过来的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics