新方法是使用集成器注册事件侦听器。Hibernate现在将使用服务发现来注册事件侦听器,以下是我如何使用maven原型web应用程序使其工作。
在 META-INF/services(应位于您的资源目录下)下创建一个名为 org.hibernate.integrator.spi.Integrator 的文件,其中包含实现休眠 spi 接口的所有类,每个类一行。下面是一个简短的示例:
...
META-INF/services/org.hibernate.integrator.spi.Integrator
com.example.CustomIntegrator
com.example.CustomIntegrator
package com.example;
import ...;
public void CustomIntegrator implements Integrator {
static final Logger logger = LoggerFactory.getLogger(CustomIntegrator.class);
@Override
public void integrate(Configuration configuration, SessionFactoryImplementor implementor, SessionFactoryServiceRegistry registry) {
final EventListenerRegistry eventRegistry = registry.getService(EventListenerRegistry.class);
logger.info("Registering event listeners");
// you can add duplication strategory for duplicate registrations
...
// prepend to register before or append to register after
// this example will register a persist event listener
eventRegistry.prependListeners(EventType.PERSIST, myListener);
...
}
...
}
com.example.MyListener
package com.example;
import ...
public class MyListener implements PersistEventListener {
static final Logger logger = LoggerFactory.getLogger(MyListener.class);
public void onPersist(PersistEvent event) throws HibernateException {
logger.debug("Entering MyListener");
if(event.getObject() instanceof MyPersistableEntity) {
MyPersistableEntity entity = (MyPersistableEntity) event.getObject();
// do something with entity
...
}
}
...
}
任何需要将此事件注册到它的实体都必须实现 MyPersistableEntity(此处未显示)