您的位置:首页 > 其它

关于Hibernate3.2的count返回值的问题

2008-07-25 16:13 375 查看
我的代码如下[/b]
@Override
  public int countAllSubject() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    return ((Long) session.createQuery(
        "select count(*) from Post where idParent=0").iterate().next())
        .intValue();
  }
问题关键在那个
(Long)
在我的机器上运行正常,可在一些网友的机器上运行报错
java.lang.ClassCastException: java.lang.Integer

他们修改成(Integer)则运行正常

我的机器上如果改成Integer,则会报错。
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

经排查,最终确定:[/b]

由于我使用的是Hibernate 3.2版本,经确认,这个版本已经把以前返回 Integer的改成了 Long,
因为JPA里面的返回值规定是Long, Hibernate为了兼容这个,所以修改了返回值。

如果你从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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: