Search code examples
javaspringhibernatehibernate-criteria

Criteria sum projection


I try to sum a column, but I get a null pointer exception and I don't know what I do wrong.

ChartVentaVendedores chart = new ChartVentaVendedores();
Criteria facturas = getSession().createCriteria(Factura.class);
facturas.add(Restrictions.like("estado", "CONFIRMADO"));
facturas.add(Restrictions.between("fechaCreacion", fromDate, toDate));

Criteria vendedorFactura = facturas.createCriteria("idVendedor");
vendedorFactura.add(Restrictions.eq("idUsuario", idVendedor));
facturas.setProjection(Projections.sum("total"));

Long counter = (Long) facturas.uniqueResult();
int value = counter.intValue();
chart.setValue(counter.intValue());            
chart.setDate(fromDate);

Even if I didn't do the join, I still get the null.

I tried to change the type of Long counter = (Long) facturas.uniqueResult(); to BigInteger but I still get the same error.

My class:

@Entity
@Table(name = "factura")
public class Factura implements Serializable {

    private int idFactura;
    private Cliente cliente;
    private String estado;
    private Usuarios idVendedor;
    private Date fechaCreacion;
    private Date fechaModificacion;
    private Integer usuarioCreacion;
    private Integer usuarioModificacion;
    private BigInteger total;
    private String tipoFactura;

    ....
}

Solution

  • I think, that your Projections.sum("total") can't sum BigInteger as it doesn't have autoboxing.

    If you can, try change BigInteger to Integer or Long.