Search code examples
hibernatetransactions

Hibernate, listen or override to opneSession from a sessionFactory.openSession()


The thing is that if you use

properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");

Then Hibernate will put only sessionFactory.getCurrentSession() calls on threadlocal and not sessionFactory.openSession() calls.

getCurrentSession gets delegated to the CurrentSessionContext but openSession do not and they do not register either.

This is problematic if someone is attempting to register those as well. We want to use a ThreadLocal List where getCurrentSession will use the last on stack.

The current implementation seems to think that there is no need to manage also openSession calls, since they could not forsee some other potential use ( more correct use ).

So, am i left with overriding the entity SessionFactoryImpl class to hook in, or is there some event that is triggered and I can hook into when a Session opens?


Solution

  • Looking at the source code, there's no way to plug into the behaviour of openSession. You could wrap your session factory in a SessionFactoryDelegatingImpl to reduce boilerplate.

    Hooking into getCurrentSession is much easier, you will simply need to implement a custom org.hibernate.context.CurrentSessionContext.