Spring Transactions Flashcards
On which layer should transaction be applied? Dao or data layer vs serivce or business logic layer?
Transactions should be applied on Service layer or Business logic layer.
Which annotation is used for specifying transactional?
@Transactional
How are transactions managed in spring technically?
ThreadLocal and AOP are used together to manage transactions in Spring.
If you have two databases is it possible to have two different transaction managers and provide detail in annotation as to which should be injected in Bean or Repository?
Yes it is possible to do that.
First we need to define two transaction managers with different qualifiers.
bean id=”tm1” class=”…JpaTransactionmanager”
property name=”entityManagerFactory” ref=”entityManagerFactory1”
qualifier value=”account”
bean id=”transactionManager2” class=”…JpaTransactionManager”
property name=”entityManagerFactory” ref=”entityManagerFactory2”
qualifier value=”businessData”
Then this qualifier can be used in annotation to specify which transaction manager should be used.
public class TransactionalService {
@Transactional("account") public void doSomethingToAccount() {}
@Transactional(“businessData”)
public void doSomethingInBusinessData() {…}
}
Transaction management can be done in how many ways with Spring?
In two ways, declarative transaction management which is high level one, using annotation. Or Programmatic transaction management, which is more advanced and flexible.
By default Spring transaction management is single threaded or multi-threaded?
Spring transactions work well with single thread, as they heavily use ThreadLocal for handling transactions. Problem arises when need to manage transactions across multiple threads.
How does spring declarative transaction management work?
It uses AOP proxies and the transactional advice is driven by metadata. 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.
Flow of declarative transaction management
Caller => AOP Proxy => Transaction Advisor (transaction created on way in and committed or rolled back on way out) => Custom Advisor (Custom interceptors may run before or after the transaction advisor) => Target method (Business logic) => Custom Advisor => Transaction Advisor => AOP Proxy => Caller