If we go with programmatic transaction, we write
Session session=sessiongFactory.openSession();
Transaction tx=session.buildTransaction();
And for a session we can build as many transaction we want.
So, We have first session object than we get Transaction Object.
While in Declarative Transaction,If we declarative @Transaction annotation at service level.
"When this Service Method will be called,Transaction will be Open" so here there is not any inforamtion about Session.
Then in Dao we write
Session session=sessiongFactory.getCurrentSession();
Here we have first Transation then Session,
Can any one please help me in understanding ,How spring manages this Declarative Transaction.
According to documentation method sessiongFactory.getCurrentSession() obtains the current session, and"current session" means controlled by the CurrentSessionContext impl configured for use.
Documentation also provides this explanation for backwards compatibility: if a CurrentSessionContext is not configured but a JTA TransactionManagerLookup is configured, this will default to the JTASessionContext impl.
JTASessionContext implementation will generate Sessions as needed provided a JTA transaction is in effect. If a session is not already associated with the current JTA transaction at the time currentSession() is called, a new session will be opened and it will be associated with that JTA transaction.
With Spring declarative transaction management you can apply @Transactional at both method & class level. It is enabled via AOP proxies. The combination of AOP with transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction with an appropriate PlatformTransactionManager implementation to drive transactions around method invocations.
Conceptually, calling a method on a transactional proxy looks like this…

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings.
All transactions are associated with the session. Transactions are initiated on the service layer but they have to be associated with a session to be committed. First transaction completes then session is closed. A session can also span several transactions. If you are using hibernate, spring uses hibernate managed transaction manager which is responsible for associating transactions with hibernate session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With