@Override
public int countConcernsMe(int companyId) throws Exception {
SessionFactory sf=super.getHibernateWriteTemplate().getSessionFactory();
Session session=SessionFactoryUtils.getSession(sf,true);
StringBuffer hql=new StringBuffer();
hql.append("SELECT COUNT(*) FROM CONE_ME WHERE CN_COMPANY_ID='"+companyId+"'");
Query query=session.createSQLQuery(hql.toString());
int number= ((Number)query.uniqueResult()).intValue();
return number;
}
从Hibernate 3.0.x/3.1.x升级到最新的3.2版之后,3.2版的很多sql函数如count(), sum()的唯一返回值已经从Integer变为Long.
这个变化主要是为了兼容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();
或者:
//参考代码
//第一种方法:
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();