Reputation: 1313
I'm using spring-data and spring-data-jpa.
I have an entity with @EntityListeners defined for both @PrePersist and @PreUpdate.
I created an entity and called thingService.save(thing). The @PrePersist listeners were called.
IN THE SAME TRANSACTION, I then called thing.setBar(bar) and then called thingService.save(thing) to update thing.
THIS TIME the @PreUpdate listeners were not called.
I haven't found any documentation which describes this behavior. Whey isn't @PreUpdate called when calling service.save(), which in turn calls thingRepository.save(thing).
Upvotes: 3
Views: 3192
Reputation: 81862
The JPA Specification basically has a verbatim answer to the question:
The PreUpdate and PostUpdate callbacks occur before and after the database update operations to entity data respectively. These database operations may occur at the time the entity state is updated or they may occur at the time state is flushed to the database (which may be at the end of the transaction).
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.
The reason behind this is (I guess) that the update might never happen. Instead the persist operation puts the entity in the persistence context. Any change to it just changes it and when it gets flushed to the database just an insert is performed. No update involved.
Upvotes: 3