Why @PreUpdate run in every query in JPA?

Viewed 392

I'm using @PreUpdate annotation in an entity class in Spring project as follow:

@Entity
public class Room {
   @Id
   @GeneratedValue
   private Long id;
   
   // Other fields and Getters and Setters

   @PreUpdate
   public void preUpdate(){
         System.out.println("pre Update");
   }
}

Now in every query, preUpdate method called, Even query to another entities. Is this logic is correct? I think It's a bit illogical.

1 Answers

A query triggers a flush of the first level cache. This in turn triggers calls to preUpdate of the entities considered dirty, i.e. in need of flushing.

The reason for the flush is that JPA can't really tell how the changed state of entities might affect the result of the query.

So if you have for example a process where you load a bunch fo entities, then change them one by one based on some additional query you are basically alternate between editing and querying and causing flushes and therefore calls to preUpdate all the time.

So as far as we can tell from your question this seems to be completely as expected.

Related