java - 如何在 Hibernate 中使用单独的队列填充实体的字段?

标签 java hibernate orm jpa

我有一个实体,比如说

@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/

相关文章:

java - 在 servlet 中通过 Hibernate 连接数据库

java - Hibernate + MySQL简单批量插入极慢

java - Hibernate 缓存 - 空表

javascript - 在不选择的情况下对连接表进行序列化

java - JPA需要外键吗

java - 在 Android 中取消应用内计费订阅

java - JPanel 中的不可见 JButton

java - 我将如何添加注释以从 jacoco 代码覆盖率报告中排除方法?

java - 使用 Transformer 将实体映射到 DTO 时获取实体内的集合

Spring引导2.1.2, hibernate 5 : Register Hibernate Event Listeners (Insert/Update/Delete)