This document discusses JPA lifecycle events and callback methods. It provides details on the different callback methods like @PrePersist, @PostPersist, etc. and describes what they are used for. It also discusses using entity listeners to attach listener classes to entities to handle lifecycle events. Multiple listener classes can be attached to a single entity class. The example shows using callbacks to automatically write user ID and timestamps to the database on inserts and updates.
2. 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.
3. Callback Methods
Callback 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).
5. Using Entity Listeners
The listener class is attached to the entity class using the
@EntityListeners annotation
Multiple listener classes can also be attached to one entity class
8. Schema
We intend to utilize JPA callback method to write user id and update
timestamp into database automatically to ease programmers’ efforts.
9. Using Callback Methods
Multiple events can be assigned to
a single method as well. This method
Will be triggered before insert and update.
10. 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.