gpt4 book ai didi

java - 如何使用@PrePersist 的 EntityManager?

转载 作者:行者123 更新时间:2023-11-30 06:36:01 24 4
gpt4 key购买 nike

我有这个“架构”的“发布”实体/表:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
int id;

@GeneratedValue(strategy = GenerationType.AUTO)
private Integer postId;

private Integer revisionId;
private Boolean isCurrentRevision;

因此,表格包含帖子,每个帖子都有多个修订版,但只有其中一个(对于每个帖子)是最新的。

现在,假设我想保留现有帖子的另一个修订版(即更新帖子):

我需要为这个 postId 找到最高的现有 revisionId,增加它并将它设置为 revisionId。此外,这是新的当前修订版,因此应相应地进行标记,但以前的当前修订版也应取消标记。

但是我该怎么做呢?我觉得这真的应该是实体实现的一部分,但另一方面我需要 EntityManager 来做到这一点。但是我找不到注入(inject) EntityManager 实例的方法(保证存在)。

这可能吗?你如何实现这样的场景?谢谢!

最佳答案

不幸的是,对于您提出的建议,没有干净、便携的方法。 JPA 2 规范 ( JSR 317 ) 声明如下:

In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context.

就实现而言,Hibernate 明确禁止它:

A callback method must not invoke EntityManager or Query methods!

我知道这不是您真正希望的,但看来您必须将修订管理责任分配给实体类的客户。

关于java - 如何使用@PrePersist 的 EntityManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5267408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com