@PreUpdate不适用于Spring Data JPA [英] @PreUpdate does not work with Spring Data JPA

查看:877
本文介绍了@PreUpdate不适用于Spring Data JPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体:

@Entity
@EntityListeners(MyEntityListener.class)
class MyEntity{ ... }

听众:

class MyEntityListener{
    @PrePersist
    @PreUpdate
    public void doSomething(Object entity){ ... }
}

我正在为此实体(1.4.1)和EclipseLink使用Spring Data生成的DAO。代码行为如下:

I'm using the Spring Data generated DAO for this entity (1.4.1) and EclipseLink. The code behavior is as follows:

MyEntity entity = new Entity();
entity = dao.save(entity); // the doSomething() is called here
// change something it the entity and save it again
dao.save(entity); // the doSomething() is NOT called here, checked with breakpoint

问题已经是有人在2009年描述,然而,他们没有提出任何解决方案。我想知道是否有人有想法如何解决它?

The problem has already been described by someone in 2009, however, they did not came up with any solution. I wonder if anyone has and idea how to solve it?

推荐答案

如你所说,回调方法被称为第二次,如果实体已从DB分离或再次获取。

As you said, the callback method is called the second time, if the entity is detached or fetched again from DB.

我无法准确解释,但可以想到所描述的情景 here ,在第二个 save()调用之前没有识别脏字段,因此未调用@PreUpdate回调。或者它可能只是您的EclipseLink版本中的一个错误。

I cannot explain it exactly, but can think of the scenario described here, when no dirty fields are identified before the second save() call and thus the @PreUpdate callback not called. Or it may be simply a bug within your version of EclipseLink.

UPDATE

在JPA 2.0规范中,我发现了以下内容,这正是您的行为(3.5.2实体生命周期回调方法的语义):

In the JPA 2.0 specification I found the following, which is exactly your behaviour (3.5.2 Semantics of the Life Cycle Callback Methods for Entities):


请注意,在实体持久化时是否发生PreUpdate和
PostUpdate回调以及随后在单个中修改
是依赖于实现的交易或当一个实体被修改为
并随后在单个交易中被移除时。
便携式应用程序不应该依赖这种行为。

Note that it is implementation-dependent as to whether PreUpdate and PostUpdate call- backs occur when an entity is persisted and subsequently modified in a single transaction or when an entity is modified and subsequently removed within a single transaction. Portable applications should not rely on such behavior.

这篇关于@PreUpdate不适用于Spring Data JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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