Hibernate-hibernate 中 Long 与 int 的转换

来源:互联网 发布:java线程池使用demo 编辑:程序博客网 时间:2024/06/13 11:59

hibernate 中使用聚合函数 count 查询记录数时,返回值类型为 Long ,若强行转换则会出现 java.lang.ClassCastException 异常,

正确写法应使用 Number 类型作为过渡则不会出错。


错误写法:

@Overridepublic int findCountByCid(Integer cid) {String hql = "SELECT count(*) from Product p WHERE p.categorySecond.category.cid = ?";Query query = getSession().createQuery(hql).setInteger(0, cid);List<Integer> list = query.list();//返回值类型应为 Long 强行转换 Integer int result = list.get(0);//调用将会出现异常return result;}


更正后:

@Overridepublic int findCountByCid(Integer cid) {String hql = "SELECT count(*) from Product p WHERE p.categorySecond.category.cid = ?";Query query = getSession().createQuery(hql).setInteger(0, cid);List<Long> list = query.list();//修正部分int result = ((Number)list.get(0)).intValue();//修正部分return result;}


0 0
原创粉丝点击