如何从@PrePersist使用EntityManager? [英] How to use EntityManager from @PrePersist?

查看:517
本文介绍了如何从@PrePersist使用EntityManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此架构发布实体/表格:

I have "post" entity/table with this "schema":

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

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

private Integer revisionId;
private Boolean isCurrentRevision;

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

So, table contains posts, each of them has multiple revisions, but only of them (for each post) is current.

现在,假设我想继续修改现有帖子(即更新帖子):

Now, let's say I want to persist another revision of existing post (i.e. update post):

我需要为这个postId找到最高的现有版本ID,增加它并将其设置为revisionId。这也是新的当前版本,所以应该相应地进行标记,但前一个版本也应该没有标记。

I need to find highest existing revisionId for this postId, increment it and set it to revisionId. Also this is the new current revision and so it should be marked accordingly, but also the former current revision should be unmarked.

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

But how can I do this? I feel that this should really be part of entity implementation but on the other hand I need EntityManager to do this. But I can't find a way to inject EntityManager instance (which is guaranteed to exist).

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

Is it possible? How do you implement such scenarios? Thanks!

推荐答案

不幸的是,没有干净,便携的方式来解决你的建议。 JPA 2规范( JSR 317 )声明如下:

Unfortunately, there is no clean, portable way to what you propose. The JPA 2 specification (JSR 317) states the following:


通常,可移植应用程序的生命周期方法不应调用EntityManager
或Query操作,访问其他实体实例或修改$内的关系b $ b相同的持久化上下文。

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明确禁止它:

As far as implementations go, Hibernate forbids it explicitly:


回调方法不能调用EntityManager或Query方法!

A callback method must not invoke EntityManager or Query methods!

我知道它是并不是你真正想要的,但似乎你必须将修订管理职责分配给你的实体类的客户。

I know it's not really what you were hoping for, but it seems that you will have to allocate the revision management responsibility to the clients of your entity class.

这篇关于如何从@PrePersist使用EntityManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆