JPA @PrePersist and @PreUpdate order when using inheritance
Asked Answered
E

2

7

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?

Ecesis answered 1/12, 2014 at 21:2 Comment(0)
R
7

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

Retractor answered 7/4, 2015 at 12:20 Comment(1)
dont put links as it is put some important portions for the samePresumptive
M
1

For me the solution was use the annotation

Example:

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import java.time.LocalDateTime;

@Data
@MappedSuperclass
public abstract class AuditObject {

    @Column(name = "dat_created")
    private LocalDateTime createdAt;

    @PrePersist
    public void onPrePersist() {
        this.createdAt = LocalDateTime.now();
    }

}

@Entity
public class Person extends AuditObject {

}
Mettlesome answered 24/3, 2022 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.