简体   繁体   English

有没有办法在其他实体更新后更新实体?

[英]is there a way to update an entity after any update of other entities?

I got a project in spring and I want to set a flag on a entity meaning that any other entities are modified.我在春天有一个项目,我想在一个实体上设置一个标志,这意味着任何其他实体都被修改了。 So on any update on these entities i have to do another update on my entity.因此,在对这些实体进行任何更新时,我必须对我的实体进行另一次更新。 Do you know a correct way to do this?你知道这样做的正确方法吗?

You can do it like this, credit to this answer你可以这样做,归功于这个答案

@Component
public class MyEventListener implements PreInsertEventListener {

    private static final long serialVersionUID = 1L;

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Autowired
    private AuditRepository auditRepository;

    @PostConstruct
    private void init() {
        SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(this);
    }

    @Override
    public boolean onPreInsert(PreInsertEvent preInsertEvent) {
        Object entity = preInsertEvent.getEntity();
        if (Customer.class.isInstance(entity)) {
            auditRepository.save(new Audit("inserted " + entity));
        }
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM