3

I have 100 entities in db. I want to get sum by some property of first 20 entities

Criteria cr = getSession().createCriteria(Entity.class);
cr.setFirstResult(0);
cr.setMaxResults(20);
cr.setProjection(Projections.sum("propertyName"));
Double sum = cr.uniqueResult();

but criteria returns sum of all entities because setMaxResults(20) restricts sum values result and that is one object - uniqueResult. Mean that construction is incrorrect. How to get sum of several entities using criteria properly?

dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
Nawa
  • 2,058
  • 8
  • 26
  • 48

1 Answers1

6

If you cannot add a constraint on the ID (e.g. .add(Restrictions.le("id", 20)); this would work if the IDs are in order), then the only possible solution I see is to split in in 2 Criterias:

// First, fetch first 20 elements' ids
List<Integer> ids = session.createCriteria(Entity.class)
        .setProjection(Projections.property("id"))
        .setMaxResults(20)
        .list();

// Afterwards, do a sum on the desired field
Long sum = (Long) session.createCriteria(Entity.class)
        .setProjection(Projections.sum("propertyName"))
        .add(Restrictions.in("id", ids))
        .uniqueResult();
Raul Rene
  • 10,014
  • 9
  • 53
  • 75