Search code examples
javahibernateormhibernate-5.xentitylisteners

Hibernate 5 entity listeners with Guice


I'm playing with the new Hibernate 5 Bootstrap API and was excited to see how easily (compared to previous/legacy API) can assemble SessionFactory and family.

Now, I would like to provide my own ListenerFactory which basically delegates creation and dependency injection of entity listeners to Guice.

I couldn't find how to do it except for applyBeanManager from SessionFactoryBuilder:

sessionFactoryBuilder.applyBeanManager(new ListenerFactory() {
  @Override
  public void release() {
  }

  @Override
  public <T> Listener<T> buildListener(final Class<T> listenerClass) {
    return () -> injector.getInstance(listenerClass);
  }
});

Unfortunately, this didn't work bc Hibernate expect ListenerFactory to be null (and uses a default ListenerFactory) or be an instance of BeanManager.

Wonder if there is another way of provide my own ListenerFactory?

Thanks.


Solution

  • That's because the BeanManager is designed for CDI. If you want to customize it beyond CDI, you need to open JIRA issue describing your use case and what you want to do.

    Alternatively, if you want to inject dependencies into your entities (which I find really odd since it breaks layer encapsulation), you could just use the LoadEventListener to customize the way an entity is created:

    sessionFactory
    .getServiceRegistry()
    .getService( EventListenerRegistry.class )
    .prependListeners( EventType.LOAD, new MyGuiceEntityListener() );