如何使用Hibernate Projection设置默认的零SUM值?

时间:2015-11-06 13:07:50

标签: java hibernate spring-mvc hibernate-criteria

我目前正在使用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));

有什么想法吗?

1 个答案:

答案 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"));