How to use @Transactional in Spring?

In Spring, the @Transactional annotation is used to indicate that a method or class should be managed by a transaction manager. When a method marked with this annotation is called, Spring automatically creates a transaction, and commits or rolls it back after the method has finished executing.

When using the @Transactional annotation, you can use it at either the method level or the class level.

  1. Method-level usage:
    The @Transactional annotation can be directly placed on a method to indicate that the method should be executed within a transaction.
  2. The user’s information is saved using the @Transactional annotation.
  3. Class-level usage:
    The @Transactional annotation can also be placed on the definition of a class, indicating that all public methods within that class should be executed within a single transaction.
  4. @Transactional
    public class UserService {
    public void addUser(User user) {
    userRepository.save(user);
    }
    }

Notice:

  1. By default, Spring will rollback the transaction if any uncaught exceptions are thrown in the method. If you want to customize the rollback condition, you can use the rollbackFor attribute of the @Transactional annotation.
  2. The @Transactional annotation can accept additional properties such as isolation (transaction isolation level), propagation (transaction propagation behavior), readOnly (whether the transaction is read-only), etc. You can customize these properties based on your own requirements.

It is important to note that in order to use the @Transactional annotation, you need to make sure that you have configured a transaction manager in your Spring configuration file, such as DataSourceTransactionManager, and have enabled transaction management with @EnableTransactionManagement annotation.

Additionally, you can use the @Transactional annotation at the class level or method level for more granular transaction control.

bannerAds