对Hibernate sum函数的使用之分析

开发
本文向您介绍使用Hibernate的sum函数进行数据的统计时,出现的错误代码以及相关的解决办法。

在使用Hibernate的sum函数进行数据的统计时,出现一个错误代码:

Java代码

String sql = "select SUM(nf.fee) from CFee as nf where   nf.adminAccount='testaccount' ";
public long getListSqlCountsLong(String sql) {
beginTransaction();
List li = getSession().createQuery(sql).list();
if (li == null || li.isEmpty()) {
return 0;
} else {return ((Integer) li.get(0)).longValue();
}
}
String sql = "select SUM(nf.fee) from CFee as nf where   nf.adminAccount='testaccount' ";
public long getListSqlCountsLong(String sql) {
beginTransaction();
List li = getSession().createQuery(sql).list();
if (li == null || li.isEmpty()) {
return 0;
} else {return ((Integer) li.get(0)).longValue();
}
}

这样使用报null错误.
List的size明明等于1,但li.get(0)还是为空.(数据库中查询的账号sum本来就为null??可能是.)
解决方法:

Java代码

String sql = "select SUM(nf.fee) from CFee as nf where   nf.adminAccount='testaccount' ";
public long getListSqlCountsLong(String sql) {
beginTransaction();
List li = getSession().createQuery(sql).list();
if (li == null || li.isEmpty()) {
return 0;
} else {
if (li.get(0) == null) {
return 0;
}
return ((Integer) li.get(0)).longValue();
}
}
String sql = "select SUM(nf.fee) from CFee as nf where   nf.adminAccount='testaccount' ";
public long getListSqlCountsLong(String sql) {
beginTransaction();
List li = getSession().createQuery(sql).list();
if (li == null || li.isEmpty()) {
return 0;
} else {
if (li.get(0) == null) {
return 0;
}
return ((Integer) li.get(0)).longValue();
}
}
解决方法很简单,就是增加一个判断就可以了,如果li.get(0)为空,则返回0,不为空,返回值. 这样就可以解决Hibernate sum函数使用出错的问题。

【编辑推荐】

  1. 选择EJB3.0,不再需要Spring+Hibernate
  2. Hibernate一对多关系的处理
  3. Struts与Hibernate的***结合方案
  4. 浅谈Struts分页中的Hibernate如何实现
责任编辑:张攀 来源: sech.javaeye.com
相关推荐

2009-06-18 14:51:12

Hibernate缓存Hibernate

2009-06-12 15:32:01

Hibernate H

2009-06-12 15:05:03

cascadeHibernate

2014-01-03 13:27:33

PostgreSQL

2015-07-13 09:56:37

2009-06-16 14:36:54

Hibernate继承

2009-09-22 13:14:29

Hibernate gHibernate l

2017-04-24 09:20:05

Spark分析分区器

2009-09-23 16:39:51

Hibernate s

2009-09-22 13:35:04

Hibernate A

2009-09-24 12:50:23

Hibernate F

2009-06-04 10:34:19

Hibernate一对一对多关系配置

2009-09-24 09:35:47

Hibernate插入

2009-09-23 10:28:16

Hibernate映像

2009-09-21 18:00:49

Hibernate X

2009-09-28 15:38:12

Hibernate P

2009-09-22 14:23:37

Hibernate S

2009-09-23 13:33:51

Hibernate属性

2009-06-18 12:14:47

javascript 函数

2010-09-10 13:24:45

SQL求和函数
点赞
收藏

51CTO技术栈公众号