Sobes.tech
Junior — Middle

How can the functionality of the @Transactional annotation in Spring be modified to achieve the desired results?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring manages transactions at the method or class level. To modify its behavior, you can use the annotation's parameters or create custom aspects.

Main ways to modify:

  • Annotation parameters:

    • propagation — defines the behavior of nested transactions.
    • isolation — transaction isolation level.
    • timeout — transaction timeout.
    • readOnly — optimization for read-only operations.
    • rollbackFor and noRollbackFor — specify which exceptions should trigger or prevent a rollback.
  • Creating a custom aspect: You can write an aspect using Spring AOP that intercepts method calls and adds additional logic around transactions.

Example of using parameters:

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void someMethod() {
    // code
}