Hibernate - 两列求和

Hibernate - Sum two columns

各位!

我试图避免直接使用 Criteria 编写 SQL/HQL 查询,所以我想知道是否可以这样做:

我的实体:

@Entity
public class A {
   @Column
   private int a1;

   @Column
   private int a2;
   .....
}

我想做的事情:

select sum(a1 + a2) from A

直接来自 Hibernate 的文档:

HQL queries can even return the results of aggregate functions on properties:

select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat

The supported aggregate functions are:

avg(...), sum(...), min(...), max(...)

count(*)

所以SELECT sum(e.a1+e.a2) FROM Entity e应该没问题。

经过一些研究,这可以使用 Formula 注释来完成:

@Entity
public class A {
   @Column(name ="a1")
   private int a1;

   @Column(name ="a2")
   private int a2;

   @Formula("a1 + a2")
   private int a3;
   .....
}

在标准中:

Criteria cr = getInstanciaCriteria(A.class); 
cr.setProjection(Projections.projectionList().add(Projection‌​s.sum("a3"));