Lifecycle Annotations Flashcards
What
Lifecycle annotations allow you to hook into an entity’s lifecycle and execute custom logic at specific lifecycle events. These annotations are methods in the entity class that the persistence provider automatically calls.
@PrePersist
Called before an entity is persisted.
Useful for initializing or validating fields before saving.
@PostPersist
Called after an entity has been persisted.
Useful for logging or triggering additional processes.
@PreUpdate
Called before an entity is updated.
Useful for setting fields like lastModified.
@PostUpdate
Called after an entity is updated
@PreRemove
Called before an entity is removed.
Useful for cleanup tasks.
@PostRemove
Called after an entity is removed.
@PostLoad
Called after an entity is loaded from the database.
Useful for initializing transient fields.
Example
@Entity
public class Order {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true) private List<OrderItem> items = new ArrayList<>(); @PrePersist public void prePersist() { System.out.println("Preparing to persist order: " + this); } @PostPersist public void postPersist() { System.out.println("Order persisted: " + this); } }