Search code examples
javahibernatecriteriaprojection

Hibernate Criteria API: how to get the sum of all the values along two columns


the question is very simple but I cannot get something working. Say, I have the following table

|....X....|.....A.....|.....B....|
|...........|.....3.....|.....2.....|
|...........|.....1.....|.....4.....|
|...........|.....1.....|.....2.....|

I simply have to obtain the total sum of values in column A and B, so (3 + 1 + 1) + (2 + 4 + 2) = 13 and I'd like to have it with Criteria API.

I tried creating a Projection summing the values along A and a DetachedCriteriawith a similar Projection summing the values along B, but I couldn't obtain a unique result from the DetachedCriteria since it doesn't expose this method.

Any advice?


Solution

  • You can do that with sqlProjection

    .setProjection(Projections.sqlProjection("sum(A + B) as sumAB", new String[] {"sumAB"} , new Type[] {Hibernate.DOUBLE}));