发布于 2019-04-12 14:22:12
我从here找到了一个可用的解决方案。它不使用integrator,而是逐个添加所有的事件监听器。下面是我的代码:
public class RootAwareInsertEventListener implements PersistEventListener {
public static final RootAwareInsertEventListener INSTANCE = new RootAwareInsertEventListener();
@Override
public void onPersist(PersistEvent event) throws HibernateException {
final Object entity = event.getObject();
if (entity instanceof RootAware) {
RootAware rootAware = (RootAware) entity;
Object root = rootAware.getRoot();
event.getSession().lock(root, LockMode.OPTIMISTIC_FORCE_INCREMENT);
log.info("Incrementing {} entity version because a {} child entity has been inserted",
root, entity);
}
}
@Override
public void onPersist(PersistEvent event, Map createdAlready)
throws HibernateException {
onPersist(event);
}
}@Component
public class HibernateListenerConfigurer {
@PersistenceUnit
private EntityManagerFactory emf;
@PostConstruct
protected void init() {
SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PERSIST).appendListener(RootAwareInsertEventListener.INSTANCE);
registry.getEventListenerGroup(EventType.FLUSH_ENTITY).appendListener(RootAwareUpdateAndDeleteEventListener.INSTANCE);
}
}https://stackoverflow.com/questions/55607443
复制相似问题