Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA @PrePersist and @PreUpdate order when using inheritance

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?

like image 498
Aliuk Avatar asked Dec 01 '14 21:12

Aliuk


2 Answers

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

like image 143
cevantes Avatar answered Dec 09 '22 11:12

cevantes


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 {

}
like image 26
Felipe SS Avatar answered Dec 09 '22 11:12

Felipe SS