How to add a custom Hibernate FlushingEventListener with Spring Boot

I want to add a custom FlushingEventListener in spring-boot .

When Hibernate Context flushes entities, I could execute my custom logic. I have tried to use @Compontent, but it does not work.

I think maybe Hibernate Context cannot use the beans of Spring. So how can I add a custom FlushingEventListener in spring-boot? On spring-boot-data-jpa, I find there are listeners and events, so I think maybe I can create a new instance of the listener in Hibernate.

Check out this article about writing a custom FlushEventListener.

However, instead of registering it via the hibernate.integrator_provider, you need to do it like in this article.

thank you vlad maybe i can let repo.save(entity) to repo.saveAndFlush(entity) but without too much change in my code

But flushing can also occur automatically before a query gets executed, so you need to cover that use case too.

@Component
public class CostomMergeEventListener implements MergeEventListener {

    @Override
    public void onMerge(MergeEvent event) throws HibernateException {
        System.out.println("My save");
        EventSource session = event.getSession();
        session.flush();
    }
    
    @Override
    public void onMerge(MergeEvent event, Map copiedAlready) throws HibernateException {
        EventSource session = event.getSession();
        session.flush();   
        System.out.println("My save with copiedAlready");
    }
}

@Configuration
public class HibernateListenerConfigurer {

    @PersistenceUnit
    private EntityManagerFactory emf;

    @Autowired
    private CostomMergeEventListener listener;

    @PostConstruct
    protected void init() {
        SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.MERGE).appendListener(listener);
    }
}

This can be done automatically when saving.But I don’t know when the hibernate event fires.There are many different EventType in hibernate code.Where can I find documentation related to org.hibernate.event.spi.EventType.Find the documentation should help me better write the corresponding listener.Thank you vald.I want to know when EventType is triggered

The Persistence Context as well as the Interceptors and Events chapters of the Hibernate User Guide are what you are looking for.