为了在更改子代时更新父代的update UpdatedTime属性,我决定在Hibernate中使用事件侦听器。我已经阅读了许多stackoverflows问题和VladMihalcea博客,并认为我可以做到,但是我被困住了。
@Component
public class HibernateEventListenerConfig {
@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).prependListener(CustomEventListener.INSTANCE);
// registry.getEventListenerGroup(EventType.SAVE_UPDATE).prependListener(CustomEventListener.INSTANCE);
// registry.getEventListenerGroup(EventType.DELETE).prependListener(CustomEventListener.INSTANCE);
registry.getEventListenerGroup(EventType.PRE_UPDATE).prependListener(CustomEventListener.INSTANCE);
// registry.getEventListenerGroup(EventType.FLUSH_ENTITY).prependListener(CustomEventListener.INSTANCE);
}
}
我观察到的是,当我为PERSIST添加EventListener并删除时,一切都按预期工作(我看到时间已更改,并且更改已传播到数据库)。但是我有更新的问题。我尝试从VladMihalcea博客中使用SAVE_UPDATE,UPDATE,FLUSH_ENTITY,但是仍然无法看到更改传播到数据库(我已打开日志)
这是来自CustomEventListener的代码。 (当我坚持或删除子实体时,更新链和获取相关方法正确运行,因为我看到了更新)
public class CustomEventListener implements PersistEventListener, DeleteEventListener, SaveOrUpdateEventListener, PreUpdateEventListener {
public static final CustomEventListener INSTANCE = new CustomEventListener();
@Override
public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
updateRelatedObjects(event.getObject());
}
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
updateRelatedObjects(event.getEntity());
return false;
}
@Override
public void onPersist(PersistEvent event) throws HibernateException {
updateRelatedObjects(event.getObject());
}
@Override
public void onDelete(DeleteEvent event) throws HibernateException {
updateRelatedObjects(event.getObject());
}
@Override
public void onDelete(DeleteEvent event, Set transientEntities) throws HibernateException {
onDelete(event);
}
@Override
public void onPersist(PersistEvent event, Map createdAlready) throws HibernateException {
onPersist(event);
}
private void updateRelatedObjects(Object object) {
if (object instanceof BaseClass) {
BaseClass rootAware = (BaseClass) object;
rootAware.getRelated().ifPresent(BaseClass::updateChain);
}
}
}
您知道更新实体时忘记了什么吗?我错过了什么吗?如果这样,我该如何更新relatedObject?