java / intermediate
Snippet
Handling Lifecycle Hooks with JPA Entity Listeners
Entity Listeners allow you to execute logic at specific points in a JPA entity's lifecycle, such as before persistence or after loading, without modifying the entity class itself.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Entity@EntityListeners(AuditListener.class)public class Product {@Id private Long id;private String name;}public class AuditListener {@PrePersistpublic void setCreatedDate(Object entity) {System.out.println("About to persist entity: " + entity);}@PostLoadpublic void logLoad(Object entity) {System.out.println("Entity loaded from DB: " + entity);}}
spring
Breakdown
1
@EntityListeners
Specifies the class containing lifecycle callback methods for the entity.
2
@PrePersist
Marks a method to run before the entity is first saved to the database.
3
@PostLoad
Marks a method to run immediately after an entity is retrieved from the database.