Search code examples
javaspringhibernatetransactionalhibernateexception

What does it mean by "Transaction Synchronized Session" with reference to Spring-Hibernate?


Like we all know, not using the @Transactional annotation in a Spring-Hibernate application gives a Hibernate Exception:

Exception in thread "main" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

I wanted to know what does it mean by "transaction synchronized session"?


Solution

  • It is a Session whose state is synchronized with underlying transaction. For example: after transaction is completed the session closes.

    Spring manages it with TransactionSynchronizationManager that holds a set of TransactionSynchronization adapters. AbstractPlatformTransactionManager calls those adapters when performing different actions with transaction.

    Most notable synchronization is SpringSessionSynchronization. Among other things it is responsible for flushing session before commit and closing session after transaction is completed.