eventlisteners using hibernate 4.0 with spring 3.1.0.release?

asyard picture asyard · Dec 23, 2011 · Viewed 29.1k times · Source

These jars are both new released and have the latest solutions for Java EE applications. But I have a problem on specifiying hibernate listeners in hibernate.cfg.xml.

Before spring 3.1.0, LocalSessionFactroyBean was holding an attribute that keeps eventlisteners. But with 3.1.0.release there is no eventlisteners map. Now I fail keeping the track of modal objects on saveorupdate, postload etc. because they are not configured by Spring. Do you have an idea to solve this issue?

Answer

nano picture nano · Jan 25, 2012

I had the same frustrating problem. Hibernate 4 appears to have fundamentally changed the way you register for events and the Spring group has not yet caught up. Here's my annotation-based solution using an init method to register a listener:

@Component
public class HibernateEventWiring {

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private SomeHibernateListener listener;

    @PostConstruct
    public void registerListeners() {
        EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(
        EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(listener);
        registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(listener);
    }
}

An interceptor would be another fine approach, but support for interceptors was mistakenly dropped: https://jira.springsource.org/browse/SPR-8940