@PreUpdate does not work with Spring Data JPA

I have an entity:

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

And the listener:

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

I am using Spring Data generated DAO for this object (1.4.1) and EclipseLink. The behavior of the code 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 was already described by someone in 2009 , but they did not come up with any solution. I wonder if anyone has an idea and how to solve it?

+6
source share
2 answers

As you said, the callback method is called the second time if the object is detached or retrieved from the database.

I cannot explain this exactly, but I can think of the scenario described below when dirty fields were not detected before the second save() call and, therefore, @PreUpdate callback was not called. Or it could just be a bug in your version of EclipseLink.


UPDATE

In the JPA 2.0 specification, I found the following, which is exactly your behavior (3.5.2. Semantics of lifecycle callback methods for objects):

Note that this is implementation-dependent, depending on whether PreUpdate and Subsequent PostUpdate callbacks occur when an object is saved and subsequently modified in a single transaction, or when the object is modified and subsequently deleted in a single transaction. Portable applications should not rely on this behavior.

+7
source

What is your transactional setting around two different save ()?

I think that between save () / update () / merge () / persist () there will be some difference for the different state of the object (transient, permanent, disconnected), the operations do not match yours and your @PrePersist and @PreUpdate annotation entered into force.

+2
source

Source: https://habr.com/ru/post/957608/


All Articles