Chapter 14. Entity Callbacks and Listeners

When you execute EntityManager methods such as persist(), merge(), remove(), and find(), or when you execute JPA QL queries or use the Criteria API, a predefined set of lifecycle events are triggered. For instance, the persist() method triggers database inserts. Merging triggers updates to the database. The remove() method triggers database deletes. Querying entities triggers a load from the database. Sometimes it is very useful to have your entity bean class be notified as these events happen. For instance, maybe you want to create an audit log of every interaction done on each row in your database. The Java Persistence specification allows you to set up callback methods on your entity classes so that your entity instances are notified when these events occur. You can also register separate listener classes that can intercept these same events. These are called entity listeners. This chapter discusses how you register your entity bean classes for lifecycle callbacks as well as how to write entity listeners that can intercept lifecycle events on your entities.

Callback Events

An annotation may represent each phase of an entity’s lifecycle:

@javax.persistence.PrePersist
@javax.persistence.PostPersist
@javax.persistence.PostLoad
@javax.persistence.PreUpdate
@javax.persistence.PostUpdate
@javax.persistence.PreRemove
@javax.persistence.PostRemove

The @PrePersist and @PostPersist events have to do with the insertion of an entity instance into the ...

Get Enterprise JavaBeans 3.1, 6th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.