对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如何实现
THE END