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

来源:互联网 发布:c语言希尔排序算法 编辑:程序博客网 时间:2024/05/21 04:44
 我的代码如下
  @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


经排查,最终确定:

由于我使用的是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();










<script type="text/javascript"><!--google_ad_client = "pub-2908059660288034";/* 728x90,首页中间 创建于 08-8-14 */google_ad_slot = "5903610560";google_ad_width = 728;google_ad_height = 90;//--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>