JPA @PrePersist and @PreUpdate order when using inheritance

callback, inheritance, joined-subclass, jpa

Solution

Yes. First the superclass callbacks will be executed.

When an event is raised, the listeners are executed in this order:

@EntityListeners for a given entity or superclass in the array order

Entity listeners for the superclasses (highest first)

Entity Listeners for the entity

Callbacks of the superclasses (highest first)

Callbacks of the entity

For more details details read about: "Callbacks and listeners inheritance" at

https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html

Problem

Supposing the following code snippet which uses @PrePersist and @PreUpdate annotations and Joined-type inheritance: ``` @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class A { ... @PrePersist private void prePersist() { ... } @PreUpdate private void preUpdate() { ... } } @Entity @DiscriminatorValue("B") public class B extends A { ... @PrePersist private void prePersist() { ... } @PreUpdate private void preUpdate() { ... } } ``` Question: Can we rely on any order of execution of the callback methods? For example when persisting class A and B will the prePersist method in B executed before the prePersist method in A or viceversa? Can we assume that the prePersist in B will be executed before the class A is persisted?

Original source