How do you use the @Transactional annotation in Spring?
The @Transactional annotation in Spring can be used to declare transaction behavior, either at the class level or method level.
Using the @Transactional annotation at the class level indicates that all public methods in that class will be included in a single transaction. Here is an example code:
@Transactional
public class MyClass {
// methods
}
Using the @Transactional annotation at the method level indicates that the method will be included in a transaction. An example code is provided below:
public class MyClass {
@Transactional
public void myMethod() {
// method body
}
}
The @Transactional annotation can also accept some parameters to configure transaction properties, such as isolation level, propagation behavior, timeout, etc. Commonly used parameters include:
- Isolation: Specifies the isolation level for the transaction, with the default value being DEFAULT.
- Propagation: Specifies the propagation behavior of the transaction, with the default being REQUIRED.
- readOnly: Specifies whether the transaction is read-only, default is false.
- timeout: Specifies the timeout period for the transaction. The default is -1, which indicates that there is no timeout limit.
- rollbackFor: specifies which exceptions will trigger a transaction rollback.
- noRollbackFor: specify the exceptions in which the transaction should not be rolled back.
Here is the code example:
@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, readOnly = false, timeout = 60, rollbackFor = Exception.class)
public void myMethod() {
// method body
}
Note: To use the @Transactional annotation, you need to enable the transaction manager in the Spring configuration file, either through the @EnableTransactionManagement annotation or by configuring tx:annotation-driven.