我在春天有一个项目,我想在一个实体上设置一个标志,意味着修改了任何其他实体。因此,在对这些实体的任何更新中,我必须对我的实体进行另一次更新。你知道这样做的正确方法吗?
答案 0 :(得分:1)
你可以这样做,归功于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;
}
}