Skip to main content

Triggers Done The JPA Way

Posted by mkarg on January 3, 2010 at 7:00 AM PST

JPA comes with a way of doing triggers, which is pretty cool: EntityListeners. It is a simple POJO that is annotated as EntityListener, and that gets linked to the triggering event by some outside glue. That outside glue can be an XML deployment descriptor (has nothing to do with the EJB 2.1 XML deployment descriptor; is nothing else but an override to the annotations found in the Java source itself) and gives the JPA engine some additional customization "from outside the application source". The cool thing is that the JPA engine fires instances of that "outside defined" listeners, and that class can do whatever it likes to do: Accessing the entity, or even fire exceptions. The nice thing is that JPA guarantees that if there is any exception fired in such a listener, then the transaction gets rolled back.

 public final class SampleBusinessProcess {

@PrePersist
private void sampleMethod(final Car car) {
car.setNumberOfWheels(4);
}

}

 	<entity class="de.quipsy.sample.Car">
<entity-listeners>
<entity-listener
class="de.quipsy.sample.SampleBusinessProcess">
</entity-listener>
</entity-listeners>
</entity>

Cool! So finally adding a third party trigger without touching the code is as easy as: Add a short piece of XML glue, write a POJO, handle your business rule in that POJO, and your're done! Isn't that exactly like a database trigger? :-)

BTW, since the original entity's code is not touched at all, there is now finally a real separation of entity and process. So in fact, this new technology is a first step towards a clean separation of concerns.