Program guide > Access data with client applications > Cache objects and their relationships (EntityManager API) > Interacting with EntityManager

Entity listener examples

You can write EntityListeners based on your requirements. Several example scripts follow.

EntityListeners example using annotations

The following example shows the life-cycle callback method invocations and order of the invocations. Assume an entity class Employee and two entity listeners exist: EmployeeListener and EmployeeListener2.

@EntityListeners(EmployeeListener.class, EmployeeListener2.class) 
public class Employee {
    public void checkEmployeeID() {

public class EmployeeListener {
    public void onEmployeePrePersist(Employee e) {

public class PersonListener {
    public void onPersonPrePersist(Object person) {

public class EmployeeListener2 {
    public void onEmployeePrePersist2(Object employee) {

If a PrePersist event occurs on an Employee instance, the following methods are called in order:

  1. onEmployeePrePersist method

  2. onPersonPrePersist method

  3. onEmployeePrePersist2 method

  4. checkEmployeeID method

Entity listeners example using XML

The following example shows how to set an entity listener on an entity using the entity descriptor XML file:

    name="Employee" access="FIELD">
<id name="id" />
<basic name="value" />
<pre-persist method-name="onListenerPrePersist" />
<post-persist method-name="onListenerPostPersist" />
<pre-persist method-name="checkEmployeeID" />

The entity Employee is configured with a entity listener class , which has two life-cycle callback methods defined. The onListenerPrePersist method is for the PrePersist event, and the onListenerPostPersist method is for the PostPersist event. Also, the checkEmployeeID method in the Employee class is configured to listen for the PrePersist event.

Parent topic:

Interacting with EntityManager