`
fantaxy025025
  • 浏览: 1251539 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

Hibernate_count_sum_统计函数的返回结果类型_与怎样兼容

阅读更多

今天碰到一个Hibernate的问题,记录一下。

在本机测试可以通过的代码,上传如公司Beta环境测试,报错:failureReason=java.lang.Integer cannot be cast to java.lang.Long

查找bug原来在统计函数:count(*)的返回结果处出错。

 

原因:

从Hibernate 3.0.x/3.1.x升级到最新的3.2版之后,3.2版的很多sql函数如count(), sum()的唯一返回值已经从Integer变为Long,如果不升级代码,会得到一个ClassCastException。

 

解决方法:

返回的结果既然类型不一样,那怎样兼容呢?用父接口统一表示。

(1)返回结果用Number标识。

(2)取值的时候根据个人喜好用Number的方法(如下),个人推荐用longValue ()方法。

 

java.lang.Object

    ----java.lang.Number

byteValue

doubleValue

floatValue

intValue

longValue

shortValue

 

例子:

//报错的写法:

Long count = (Long) session.createQuery(hql.toString())
                .setParameter("customerInvoiceInfoId", customerInvoiceInfoId)
                .setParameter("customerId", customerId)
                .uniqueResult()
                ;

if(count > 0) {
            return true;
        }else{
            return false;
        }

}

 

//正确的写法

Number count = (Number) session.createQuery(hql.toString())
                .setParameter("customerInvoiceInfoId", customerInvoiceInfoId)
                .setParameter("customerId", customerId)
                .uniqueResult()
                ;
        if(count.longValue() > 0) {
            return true;
        }else{
            return false;
        }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics