How to use spring transaction in multithread

No, methodB() will not be executed in the same transaction as methodA(). Spring’s @Transactional only works on a single thread – it creates a session when a thread first enteres a method with @Transactional (or a method in a class with @Transactional), and then commits it when it leaves that method. In your example, the … Read more

Transactional saves without calling update method

Because hibernate will automatically detect changes made to persistent entities and update the database accordingly. This behaviour is documented in chapter 11 of the hibernate reference manual. The relevant part reads: Hibernate defines and supports the following object states: Transient – an object is transient if it has just been instantiated using the new operator, … Read more

Spring @Transactional not working

The reason that moving the context:component-scan tags to the application context xml fixed the transactional behavior is: <tx:annotation-driven /> is a post-processor that wraps @Transactional annotated bean methods with an AOP method interceptor which handles transactional behavior. Spring post-processors, only operate on the specific application context they are defined in. In your case, you have … Read more

Why we shouldn’t make a Spring MVC controller @Transactional?

TLDR: this is because only the service layer in the application has the logic needed to identify the scope of a database/business transaction. The controller and persistence layer by design can’t/shouldn’t know the scope of a transaction. The controller can be made @Transactional, but indeed it’s a common recommendation to only make the service layer … Read more

Spring @Transactional – isolation, propagation

Good question, although not a trivial one to answer. Propagation Defines how transactions relate to each other. Common options: REQUIRED: Code will always run in a transaction. Creates a new transaction or reuses one if available. REQUIRES_NEW: Code will always run in a new transaction. Suspends the current transaction if one exists. The default value … Read more

Spring – @Transactional – What happens in background?

This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring’s declarative transaction support uses AOP at its foundation. But at a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. … Read more