JPA Listeners & Callbacks Annotations

Jakarta Persistence (JPA) provides lifecycle callback annotations to trigger custom logic during specific entity state transitions. These annotations allow you to define methods within an entity or a listener class.

Listeners configuration

Entity

Entities and mapped superclasses can be further configured with annotations that specify lifecycle event listeners.

Specifies one or more callback listener classes for the entity or mapped superclass. These listeners respond to lifecycle events (for example, PrePersist and PostLoad).

Specifies that the default listeners defined for the persistence unit are not applied to this class.

Specifies that listeners declared in superclasses are not applied to this class.

Persistence (creation) events

Use these annotations to handle logic when saving new entities to the database:

Executes before the EntityManager persist operation. This is useful for initializing default values or creation timestamps.

Executes after the entity is persisted to the database, making the generated primary key available.

Update events

Handle events triggered when modifying existing entities and flushing changes to the database:

Executes before the database update operation. This is typically used to update "last modified" timestamps or validate state changes.

Executes after the database update operation has completed.

Removal events

Manage cleanup tasks when deleting entities from the database:

Executes before the removal operation, allowing cleanup of related non-persistent resources.

Executes after the entity has been removed from the database.

Load events

Trigger logic after retrieving data from the database:

Executes after an entity is loaded into the persistence context or refreshed. This is useful for initializing transient fields or performing post-load calculations.

The Lifecycle Events section of the ObjectDB Manual explains how to use these annotations with callback methods and listener classes.