Search code examples
javaspringhibernatespring-transactionshibernate-session

Listener on transaction start


I am looking for a clean solution to have a listener for transaction start. That means I would like the listener to be a bean (component) in the spring context that would receive an event on transaction start from TransactionPlatformManager or Hibernate Session or something similar, at the point where a new transaction is started.

Something along:

@Component
class TransactionListener implements ?? {

    @Autowired
    private Something x;

    public void onTransactionBegin(...) {
        x.doSomething()
    }

}

To be concrete, I am mitigating a system wide problem and I need to set a thread local when transaction starts, so I can access that thread local further in the processing of hibernate entities to retrieve info.

I looked into sources and found no traces for such listener to be achievable. The only solution I found was to subclass HibernateTransactionManager and its doBegin() method, which I don't find particularly nice.


Solution

  • Spring have some transaction callbacks in its TransactionSynchronization, however as you correctly have noticed, there is no callback for transaction start, my mistake.

    As far as I know, Spring will not let you know when transactions start, although this may vary from different implementations PlatformTransactionManager. If you want to hook into Spring transaction, I believe you are left with

    1. Subclass the transaction manager and invoke some callback
    2. Create an advice for @Transactional with spring-aop (this will only work if you use annotations, obviously)

    If you're using Hibernate, you might have some luck with afterTransactionBegin in https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Interceptor.html#afterTransactionBegin(org.hibernate.Transaction)