简体   繁体   中英

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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