我有一个实体,比如说
@Entity
public class Category {
private String name;
private int usersInCategory;
}
我想用一些聚合 SQL 查询填充 usersInCategory 字段(select count(*) ... group by ...
)。
如何在 Hibernate 中执行此操作?
最佳答案
使用 Formula
(这是 Hibernate 特定的注释)。来自文档:
2.4.3.1. Formula
Sometimes, you want the Database to do some computation for you rather than in the JVM, you might also create some kind of virtual column. You can use a SQL fragment (aka formula) instead of mapping a property into a column. This kind of property is read only (its value is calculated by your formula fragment).
@Formula("obj_length * obj_height * obj_width") public long getObjectVolume()
The SQL fragment can be as complex as you want and even include subselects.
正如文档所写,SQL 片段可能非常复杂,并且可以引用所属实体,如下例所示(where 子句的 id
部分中的非别名 o.customer_id=id
列引用所属实体列) :
@Formula("(select coalesce(extract ('day' from age(max(o.creation_date))), 9999) from Orders o where o.customer_id = id)")
private int daysSinceLastOrder;
另请参阅
关于java - 如何在 Hibernate 中使用单独的队列填充实体的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3435541/