I have a named query that returns a Collection
of entities.
These entities have a @PreUpdate
-annotated method on them. This method is invoked during query.getResultList()
. Because of this, the entity is changed within the persistence context, which means that upon transaction commit, the entity is written back to the database.
Why is this? The JPA 2.0 specification does not mention explicitly that @PreUpdate
should be called by query execution.
Annotation Type PreUpdateSpecifies a callback method for the corresponding lifecycle event. This annotation may be applied to methods of an entity class, a mapped superclass, or a callback listener class. Since: Java Persistence 1.0.
The @PrePersist annotation is used to configure a callback for pre-persist(pre-insert) events of the entity. In other words, it is used to annotate model methods to indicate that the method should be called before the entity is inserted (persisted) into the database.
prePersist - The prePersist event occurs for a given entity before the respective EntityManager persist operation for that entity is executed. preUpdate - The preUpdate event occurs before the database update operations to entity data. It is not called for a DQL UPDATE statement.
The @PostLoad method for an entity is invoked AFTER the entity has been loaded into the current persistence context from the database or after the refresh operation has been applied to it.
The specification says:
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).
In this case calling query.getResultList()
triggers a em.flush()
so that the query can include changed from current EntityManager session. em.flush()
pushes all the changes to the database (makes all UPDATE,INSERT calls). Before UPDATE
is sent via JDBC @PreUpdate
corresponding hooks are called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With