我有一个实体:
@Entity
@EntityListeners(MyEntityListener.class)
class MyEntity{ ... }
而听众:
class MyEntityListener{
@PrePersist
@PreUpdate
public void doSomething(Object entity){ ... }
}
我正在为此实体(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
问题已经是described by someone in 2009,但是,他们没有提出任何解决方案.我想知道是否有人有想法如何解决它?
最佳答案
正如您所说,如果实体是从DB分离或再次获取的,则第二次调用回调方法.
我无法准确解释它,但可以想到here所描述的场景,在第二次save()调用之前没有识别脏字段,因此未调用@PreUpdate回调.或者它可能只是您的EclipseLink版本中的一个错误.
UPDATE
在JPA 2.0规范中,我发现了以下内容,这正是您的行为(3.5.2实体生命周期回调方法的语义):
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.