… or my urge to share knowledge

Spring managed event listeners with JPA

I wanted to set things right. I’ve been approximative in a previous post. I wrote an incomplete assertion: “using spring-managed listeners with JPA is not possible“. I want to clarify things:

– using spring managed listeners with JPA is not possible if you absolutly want to use JPA interface and ignore the underlying implementation,

– if your implementation is hibernate, and depending on hibernate version, your solution may be more or less elegant.

1 – When JPA won’t suit your needs.

JPA won’t suit your needs when you need (for many reason) to have control on the listener : the class that executes instructions as a reaction to an event.
You also may want to inject already live beans (collaborators) in the listener. If so you can’t let JPA do that wiring.

But even if you cannot provide JPA interfaces with your listeners, you’re not stuck, you can use the underlying implementation.
The key is to obtain the implementation from the interface: downcasting is a bad but can be helpful in some cases.

2 – Use Hibernate < 4.0.0.Final

The script below shows how to register spring-managed listeners in a hibernate (< 4.0.0.Final) configuration obtained from JPA.
Beware that the below code doesn’t extend hibernate’s behaviour, it modifies it: it overrides the existings Listeners array rather than extending them. A cleaner solution would leave hibernate’s behaviour intact and add listeners to existing ones.
The example uses @Autowired annotations but the same configuration can be achived with xml.

3 – Use Hibernate 4.0.0.Final and above

The script below shows how to register spring-managed listeners in an hibernate configuration obtained from JPA.
The new concept here is SPI (Service Provider Interface) which basically is a well defined extension point. It’s a very nice illustration of the Open/Closed Principle.
Hibernate provides many SPI. Among them is the event SPI which defines listeners interfaces (more than 20), events (about 30) and an EventListenerRegistry.

7 comments on “Spring managed event listeners with JPA”

While the issue appear to be well documented for hibernate 3, it is less documented for hibernate 4 and even less so when using the JPA wiring with LocalContainerEntityManagerFactoryBean and HibernateJpaVendorAdapter, which is where I got stuck.

There are also very few examples of @Component and @Configuration solutions.

Hibernate Entity Manager needs to enhance Hibernate core to implements all the JPA semantics. It does that through the event listener system of Hibernate. Be careful when you use the event system yourself, you might override some of the JPA semantics. A safe way is to add your event listeners to the list given below.

I can’t tell the exact packge but you should be able to implement some pre/post CRUD event listener from the hibernate framework for example org.hibernate.event.spi.PreDeleteEventListener
Hope this helps