jpa lifecycle events practice
TRANSCRIPT
Lifecycle Callbacks It is often necessary to perform various
actions at different stages of a persistent object's lifecycle. JPA includes a variety of callbacks methods for monitoring changes in the lifecycle of your persistent objects. These callbacks can be defined on the persistent classes themselves and on non-persistent listener classes.
Callback MethodsCallback method Description
@PrePersist before a new entity is persisted (added to the EntityManager).
@PostPersist after storing a new entity in the database (during commit or flush).
@PostLoad after an entity has been retrieved from the database.
@PreUpdate when an entity is identified as modified by the EntityManager.
@PostUpdate after updating an entity in the database (during commit or flush).
@PreRemove when an entity is marked for removal in the EntityManager.
@PostRemove after deleting an entity from the database (during commit or flush).
Using Callback Methods
Using Entity Listeners
Multiple listener classes can also be attached to one entity class
The listener class is attached to the entity class using the @EntityListeners annotation
Example
NIG005W
User uses this function to maintain organization information.
Schema
We intend to utilize JPA callback method to write user id and update timestamp into database automatically to ease programmers’ efforts.
Using Callback MethodsMultiple events can be assigned to a single method as well. This method Will be triggered before insert and update.
Using Entity Listeners
Mixing lifecycle event code into your persistent classes is not always ideal. It is often more elegant to handle cross-cutting lifecycle events in a non-persistent listener class. JPA allows for this, requiring only that listener classes have a public no-arg constructor. Like persistent classes, your listener classes can consume any number of callbacks. The callback methods must take in a single java.lang.Object argument which represents the persistent object that triggered the event.