【发布时间】:2020-12-09 14:02:17
【问题描述】:
所以我有两个具有一对多关系的实体。一个form_collection 包含多个form。 form 包含一个列 version,它跟踪最新的表单。
form
+----+-----------------+---------+--------------------+
| id | description_key | version | form_collection_id |
+----+-----------------+---------+--------------------+
| 1 | desc1 | 1 | 1 |
+----+-----------------+---------+--------------------+
| 2 | desc1 | 2 | 1 |
+----+-----------------+---------+--------------------+
| 3 | desc2 | 1 | 1 |
+----+-----------------+---------+--------------------+
| 4 | desc3 | 1 | 2 |
+----+-----------------+---------+--------------------+
form_collection
+----+-------+
| id | name |
+----+-------+
| 1 | coll1 |
+----+-------+
| 2 | coll2 |
+----+-------+
在我的 java 代码中,我只希望一对多关系仅包含具有相同描述键的每个表单的最新版本(类似于this article 中解释的软删除)。为了检索最新的表单,我想出了这个按预期工作的查询:
SELECT *
FROM form AS a
INNER JOIN (
SELECT description_key, max(version) AS version
FROM form
GROUP BY description_key
) AS b
ON a.description_key = b.description_key AND a.version = b.version;
这只会返回第 2、3、4 行。
但是,我在将其应用于具有以下实体的 Hibernate 架构时遇到问题。这种过滤可以用注解来完成吗?
@Entity
@Table(name = "form", schema = "public")
public class FormDO extends BaseDO {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "form_collection_id")
private FormCollectionDO formCollection;
}
@Entity
@Table(name = "form_collection", schema = "public")
public class FormCollectionDO extends BaseDO {
@OneToMany(mappedBy = "formCollection")
// can I add an annotation here to filter for only the once that have the highest versions?
private List<FormDO> forms;
}
可以用类似的东西来完成吗?
@Where(clause = "version = SELECT max(version) FROM form GROUP BY description_key")
【问题讨论】:
-
我遇到了this article,但我无法让它工作。
标签: spring-boot hibernate jpa