Issue
I have an entity:
@Entity
@EntityListeners(MyEntityListener.class)
class MyEntity{ ... }
And the listener:
class MyEntityListener{
@PrePersist
@PreUpdate
public void doSomething(Object entity){ ... }
}
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
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?
Solution
As you said, the callback method is called the second time, if the entity is detached or fetched again from DB.
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
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):
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.
Answered By - Andrei I