VOOZH about

URL: https://www.javacodegeeks.com/2016/07/spring-managed-hibernate-event-listeners.html

⇱ Spring-Managed Hibernate Event Listeners - Java Code Geeks


Hibernate offers event listeners as part of its SPI. You can hook your listeners to a number of events, including pre-insert, post-insert, pre-delete, flush, etc.

But sometimes in these listeners you want to use spring dependencies. I’ve written previously on how to do that, but hibernate has been upgraded and now there’s a better way (and the old way isn’t working in the latest versions because of missing classes).

This time it’s simpler. You just need a bean that looks like this:

@Component
public class HibernateListenerConfigurer {
 
 @PersistenceUnit
 private EntityManagerFactory emf;
 
 @Inject
 private YourEventListener listener;
 
 @PostConstruct
 protected void init() {
 SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
 EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
 registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(listener);
 registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(listener);
 registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(listener);
 }
}

It is similar to this stackoverflow answer, which however won’t work because it also relies on deprecated calsses.

You can also inject a List<..> of listeners (though they don’t share a common interface, you can define your own).

As pointed out in the SO answer, you can’t store new entities in the listener, though, so it’s no use injecting a DAO, for example. But it may come handy to process information that does not rely on the current session.

Reference: Spring-Managed Hibernate Event Listeners from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Bozhidar Bozhanov
Bozhidar Bozhanov
July 18th, 2016Last Updated: July 16th, 2016
0 613 1 minute read

Bozhidar Bozhanov

Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE, as well as Android, Scala and any framework you throw at him. creator of Computoser - an algorithmic music composer. Worked on telecom projects, e-government and large-scale online recruitment and navigation platforms.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz