O'Reilly logo

Enterprise JavaBeans 3.1, 6th Edition by Bill Burke, Andrew Lee Rubinger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required