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(); 
/**
  * @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也提供了一个与原来兼容的解决方案:

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();  
Configuration classicCfg = new Configuration(); 
classicCfg.addSqlFunction( "count", new ClassicCountFunction()); 
classicCfg.addSqlFunction( "avg", new ClassicAvgFunction()); 
classicCfg.addSqlFunction( "sum", new ClassicSumFunction()); 
SessionFactory classicSf = classicCfg.buildSessionFactory(); 


Java代码:
  1. //int count = ((Integer)query.uniqueResult()).intValue();  
  2. //改成  
  3.  
  4. int count = ((Number)query.uniqueResult()).intValue();  
  5.  
  6. //这样就可以两个版本同时兼容.  
//int count = ((Integer)query.uniqueResult()).intValue(); 
//改成 

int count = ((Number)query.uniqueResult()).intValue(); 

//这样就可以两个版本同时兼容. 

 

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();  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值