Chapter 10. Entity Callbacks and Listeners

When you execute EntityManager methods like persist( ), merge( ), remove( ), and find( ), or when you execute EJB QL queries, a predefined set of life cycle 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 life cycle callbacks as well as how to write entity listeners that can intercept life cycle events on your entities.

Callback Events

A certain annotation represents each phase of an entity’s life cycle:

@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 ...

Get Enterprise JavaBeans 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.