Video in progress
What are lifecycle callbacks like @PrePersist and @PreUpdate used for?
They are methods that get called automatically at certain points in an entity's lifecycle: before saving, before updating, after loading, and so on. They're mostly used to set createdAt/updatedAt, assign default values, or do simple checks.
📖 Answer
@Entity
public class Article {
@Id @GeneratedValue private Long id;
private String slug;
private String title;
private Instant createdAt;
private Instant updatedAt;
@PrePersist
void beforeInsert() {
createdAt = updatedAt = Instant.now();
if (slug == null) slug = title.toLowerCase().replace(' ', '-');
}
@PreUpdate
void beforeUpdate() {
updatedAt = Instant.now();
}
}
The full list: @PrePersist, @PostPersist, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove, @PostLoad.
If several entities share the same logic, you can move it into a separate class and attach it with @EntityListeners. Spring Data's auditing with @CreatedDate and @LastModifiedDate is built on exactly this mechanism (AuditingEntityListener).
Limitations:
@PreUpdateis called only when Hibernate really sends an UPDATE; a JPQL bulkupdateor native SQL bypasses it;- it's not recommended to run queries with the
EntityManageror modify other entities inside a callback, since the result during a flush is unpredictable.
Hibernate also has @CreationTimestamp and @UpdateTimestamp, a shorter option for timestamp fields.
Sign up to mark studied questions and save your progress.