Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a JPA @PreUpdate-annotated method get called during a query?

Tags:

jpa

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.

like image 473
Laird Nelson Avatar asked Aug 23 '12 17:08

Laird Nelson


People also ask

What is PreUpdate annotation?

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.

What is@ PrePersist annotation?

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.

What is PrePersist and PreUpdate?

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.

Which method is invoked after database update operation on entity data?

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.


1 Answers

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.

like image 164
rzymek Avatar answered Sep 21 '22 07:09

rzymek