A lifecycle callback method is invoked automatically when a persistent entity reaches a specified lifecycle event. JPA callbacks provide access to persist, load, and remove events, allowing applications to perform side effects such as audit logging or tenant assignment. section 13.2 section 13.0
Define callbacks either on an entity listener or directly on the entity class:
- An entity listener is a stateless class with an implicit or explicit public no-argument constructor; the persistence engine creates and destroys it automatically. section 13.2.1
- Annotate a listener method with an event annotation such as @PostPersist, @PostLoad, or @PrePersist. section 13.2.1
- A listener callback accepts one Object parameter, or the specific entity type when restricted to one entity. It may use any access level, but cannot be static or final and must return nothing. section 13.2.1
- An entity-class callback takes no arguments and uses this to access the current entity. A class cannot define duplicate callbacks for the same event. section 13.2.1
- Enable listener classes with @EntityListeners; multiple listeners can be declared, and callbacks for one event run in declared order. section 13.2.1
- An unchecked RuntimeException aborts the operation and marks the transaction for rollback; checked exceptions are wrapped and treated as RuntimeException. section 13.2.1
Logging after persistence
A PersistEntityListener can annotate logMessage(Object entityInstance) with @PostPersist, retrieve the current user, and save a message containing that user and the stored entity. An Item entity activates the listener with @EntityListeners(PersistEntityListener.class).
