我目前正在使用Hibernate Criteria创建一个包含SUM的摘要查询,
如果没有该值的值,我希望收到0
而不是null
,
这是我的代码
public class DetalleLibroMayor {
private Cuenta cuenta;
private BigDecimal debe = BigDecimal.ZERO;
private BigDecimal haber = BigDecimal.ZERO;
这是查询(只是投影部分)
ProjectionList projection = Projections.projectionList();
projection.add(Projections.property("cuenta").as("cuenta"));
projection.add(Projections.sum("debe").as("debe"));
projection.add(Projections.sum("haber").as("haber"));
projection.add(Projections.groupProperty("cuenta.id"));
criteria.setProjection(projection);
criteria.setResultTransformer(Transformers.aliasToBean(DetalleLibroMayor.class));
有什么想法吗?
答案 0 :(得分:0)
我终于使用MySQL的COALESCE
函数解决了这个问题并编写了我的自定义投影,如下所示:
public class CoalesceAggregateProjection extends AggregateProjection {
private static final long serialVersionUID = 1L;
private String aggregate;
private Object defaultValue;
protected CoalesceAggregateProjection (String aggregate, String propertyName, Object defaultValue) {
super(aggregate, propertyName);
this.aggregate = aggregate;
this.defaultValue = defaultValue;
}
@Override
public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery) throws HibernateException {
return new StringBuffer()
.append("coalesce(")
.append(aggregate)
.append("(")
.append( criteriaQuery.getColumn(criteria, propertyName) )
.append("),")
.append(defaultValue.toString())
.append(") as y")
.append(loc)
.append('_')
.toString();
}
public static AggregateProjection sum (String propertyName, Object defaultValue) {
return new CoalesceAggregateProjection("sum", propertyName, defaultValue);
}
}
然后按照我的标准使用它:
projection.add(CoalesceAggregateProjection.sum("debe", "0").as("debe"));