4.1.4. Using Entity Listeners

Entity listeners allow you to execute your business logic each time an entity is added, updated or removed from the database. For example, we could recalculate the discount for a customer each time an order for this customer is changed.

An entity listener stub can be easily created using Studio:

  • Switch to the Middleware section and click New > Entity listener.

  • Change the class name to OrderEntityListener and select checkboxes for BeforeInsertEntityListener, BeforeUpdateEntityListener and BeforeDeleteEntityListener interfaces.

  • Select Order entity in the Entity type field.

  • Click OK or Apply and open the listener class in your IDE.

See an example implementation in the demo application:

using entity listeners 1
  • OrderEntityListener.java - the entity listener.

  • DiscountCalculator.java - a managed bean of the middle tier which actually calculates discounts. An entity listener can contain the business logic itself, but we will use this delegate to share logic with services and JMX beans.

If you open the Logic in Entity Listeners screen of the demo application, you will see two tables: orders and customers. Create, edit or remove an order, then refresh the customers table, and you will see that the discount of the corresponding customer is changed.