@PreUpdate不适用于Spring Data JPA

fra*_*acz 7 java spring jpa spring-data-jpa

我有一个实体:

@Entity
@EntityListeners(MyEntityListener.class)
class MyEntity{ ... }
Run Code Online (Sandbox Code Playgroud)

而听众:

class MyEntityListener{
    @PrePersist
    @PreUpdate
    public void doSomething(Object entity){ ... }
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

And*_*i I 7

正如您所说,如果实体是从DB分离或再次获取的,则第二次调用回调方法.

我无法完全解释它,但是可以想到这里描述的场景,在第二次save()调用之前没有识别出脏字段,因此未调用@PreUpdate回调.或者它可能只是您的EclipseLink版本中的一个错误.


UPDATE

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

请注意,在实体持久化并随后在单个事务中进行修改或者在单个事务中修改实体并随后将其删除时,是否依赖于实现来确定是否发生PreUpdate和PostUpdate回调.便携式应用程序不应该依赖这种行为.