Objectopia

EJB 3.0 Interceptors

Posted by Chris Clark on July 21, 2009

I wanted to carry out some processing when an entity was committed to the db, I could of used the lifecycle annotation @PostPersist in the bean itself but that that would go against leaky abstraction (see post Non-anaemic models). Anywho it was pretty simple to get this working all that I had to use were a couple of annotations.

The first @EntityListerners which accepts an array of classes that will become your event handlers:

@EntityListeners(ErrorListener.class)
public class SystemError implements Serializable {

The next is to annotate the methods in your listener class that will handle the various events. The annotations that can be used are:

    @PrePersist Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.
    @PreRemove Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
    @PostPersist Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
    @PostRemove Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
    @PreUpdate Executed before the database UPDATE operation.
    @PostUpdate Executed after the database UPDATE operation.
    @PostLoad Eexecuted after an entity has been loaded into the current persistence context or an entity has been refreshed.

Note that if you are using EJB dependency injection it won’t work in your listener as it’s not managed by your container buy you can use jndi: -

Context ctx = new InitialContext();
XXXService service = (XXXService) ctx.lookup("EARNAME/XXXServiceBean/local");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.