Skip to content
Martin Ledvinka edited this page Jan 20, 2019 · 10 revisions

Entity Classes

Lifecycle Listeners

Much like JPA, JOPA supports entity lifecycle listeners. These come in two flavors:

  • Lifecycle callback methods declared on entity classes or in mapped superclasses
  • Entity listener classes

The following annotations are bound to the respective entity lifecycle events:

  • @PrePersist
  • @PostPersist
  • @PreRemove
  • @PostRemove
  • @PreUpdate
  • @PostUpdate
  • @PostLoad

Lifecycle Callbacks

Lifecycle callbacks are methods declared directly in entity classes or in mapped superclasses, annotated with the aforementioned annotations. A callback may be annotated by multiple lifecycle event annotations.

The callback may not be static, but can have arbitrary visibility. It should take no argument, as it is called on the entity instance to which the lifecycle event applies. The callback's return type must be void. Method signature should thus look as follows:

void callback();

Entity Listeners

Entity listeners are non-managed classes containing lifecycle callback methods. An entity listeners is registered for a concrete entity through the @EntityListeners annotation declared on the entity. Multiple listeners can be specified for an entity, the order of declaration specifying also the order in which their callback methods are invoked.

The callback methods are similar to those defined directly in entities (see above) but they take a single argument representing the entity for which the callback is being invoked. The type of the argument can be Object or a more specific type. The method signature should look as like this:

void callback(Object entity);

The callback method are annotated with lifecycle event annotations listed above.

Lifecycle Callback Methods Semantics

The semantics of lifecycle callback methods correspond to the semantics defined in JPA, section 3.5.3, so details can be found there. In a nutshell, PrePersist and PreRemove are invoked before the respective entity manager operations are executed. PostPersist and PostRemove are invoked after the entity has been made persistent/removed.

PreUpdate and PostUpdate occur before and after new entity state has been merged into the underlying repository. Note that if the lifecycle listener modifies the state of the entity on which it was invoked (e.g. when setting provenance data on update), the listener is not invoked again. This is to prevent endless loops.

PostLoad is invoked after the entity has been loaded into the persistence context. It also applies to query results. In case of lazily loaded attributes, the PostLoad will occur when the relationship is triggerred and the entity is loaded.

All the lifecycle operations are cascaded.

Clone this wiki locally