eventlisteners using hibernate 4.0 with spring 3.1.0.release?

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

Leave a Comment