2.4.3.3. 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.
Entities can enumerate listeners using the EntityListeners annotation.
This annotation takes an array of listener classes as its value.
Below is an example of how to declare an entity and its corresponding listener classes.
/**
* Example persistent class declaring our entity listener.
*/
@Entity
@EntityListeners({ MagazineLogger.class, ... })
public class Magazine {
// ... //
}
/**
* Example entity listener.
*/
public class MagazineLogger {
@PostPersist
public void logAddition(Object pc) {
getLog().debug("Added new magazine:" + ((Magazine) pc).getTitle());
}
@PreRemove
public void logDeletion(Object pc) {
getLog().debug("Removing from circulation:"
((Magazine) pc).getTitle());
}
}
In XML, we define both the listeners and their callback methods as so:
<entity class="Magazine">
<entity-listeners>
<entity-listener class="MagazineLogger">
<post-persist>logAddition</post-persist>
<pre-remove>logDeletion</pre-remove>
</entity-listener>
</entity-listeners>
</entity>