是的,可以在DB中提交某些更改后通知另一个进程(例如:审计).那就是使用Hibernate的自定义拦截器和事件来执行JDBC事务(Hibernate包装JDBC事务)之后的某些事情.
您可以通过使用Hibernate的EmptyInterceptor类来扩展自己的自定义拦截器类.并且在事务提交之后,通过覆盖EmptyInterceptor的AfterTransactionCompletion(Transaction tx)方法来执行某些任务.
public class AuditLogInterceptor extends EmptyInterceptor {
@Override
public void afterTransactionCompletion(Transaction tx) {
System.out.println("Task to do after transaction ");
}
}
事件系统可以作为拦截器使用,也可以替代.
下面列出的是在事务事件完成/提交后执行某些任务的几种方法
1.从org.hibernate.action包中实现AfterTransactionCompletionProcess接口,并实现以下方法. documentation
void doAfterTransactionCompletion(boolean success, SessionImplementor session) {
//Perform whatever processing is encapsulated here after completion of the transaction.
}
否则,您可以使用EntityDeleteAction扩展您的CustomDeleteAction类,并覆盖上述doAfterTransactionCompletion方法. documentation
2.实现PostDeleteEventListener并使用EventType.POST_COMMIT_DELETE进行帖子删除.
通过实现PostInsertEventListener并使用EventType.POST_COMMIT_INSERT进行后插入.
通过实现PostUpdateEventListener并使用EventType.POST_COMMIT_UPDATE进行后期更新.
以下是PostDeleteEventListener的几个例子
,PostUpdateEventListener和PostInsertEventListener.
PostInsertEvent的Object实体给出了涉及数据库操作的实体.
PostInsertEvent的Object []状态返回此事件的会话事件源.这是生成此事件的基础会话.
以下链接包含PostInsertEvent成员的文档.
注册事件监听器:MyIntegrator类下面显示注册事件侦听器的3种方式.
public class MyIntegrator implements org.hibernate.integrator.spi.Integrator {
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
// As you might expect, an EventListenerRegistry is the thing with which event listeners are registered
// It is a service so we look it up using the service registry
final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
// If you wish to have custom determination and handling of "duplicate" listeners, you would have to add an
// implementation of the org.hibernate.event.service.spi.DuplicationStrategy contract like this
eventListenerRegistry.addDuplicationStrategy( myDuplicationStrategy );
// EventListenerRegistry defines 3 ways to register listeners:
// 1) This form overrides any existing registrations with
eventListenerRegistry.setListeners( EventType.AUTO_FLUSH, myCompleteSetOfListeners );
// 2) This form adds the specified listener(s) to the beginning of the listener chain
eventListenerRegistry.prependListeners( EventType.AUTO_FLUSH, myListenersToBeCalledFirst );
// 3) This form adds the specified listener(s) to the end of the listener chain
eventListenerRegistry.appendListeners( EventType.AUTO_FLUSH, myListenersToBeCalledLast );
}
}
因此,听众对事件的注册取决于实现细节.