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?
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
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 {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.