本文共 2134 字,大约阅读时间需要 7 分钟。
-
-
-
- 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();
- }
/** * @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();
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 = ((Number)query.uniqueResult()).intValue();
-
-
//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://vrmji.baihongyu.com/