WebSphere eXtreme Scale Programming Guide > Access data in WebSphere eXtreme Scale > EntityManager API introduction > 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.

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

public class EmployeeListener {
    @PrePersist
    public void onEmployeePrePersist(Employee e) {
        .... 
    }
}

public class PersonListener {
    @PrePersist
    public void onPersonPrePersist(Object person) {
        .... 
    }
}

public class EmployeeListener2 {
    @PrePersist
    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:

<entity
    class-name="com.ibm.websphere.objectgrid.sample.Employee"
    name="Employee" access="FIELD">
   
<attributes>
       
<id name="id" />
       
<basic name="value" />
   
</attributes>
   
<entity-listeners>
       
<entity-listener
            class-name="com.ibm.websphere.objectgrid.sample.EmployeeListener">
           
<pre-persist method-name="onListenerPrePersist" />
           
<post-persist method-name="onListenerPostPersist" />
       
</entity-listener>
   
</entity-listeners>
   
<pre-persist method-name="checkEmployeeID" />
</entity>

The entity Employee is configured with a com.ibm.websphere.objectgrid.sample.EmployeeListener 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


+

Search Tips   |   Advanced Search