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

jpa

Solution

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.

Problem

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.

Original source