Transactional annotation in JPA

Transactional annotation in JPA

  • 1.  Purpose of @Transactional Annotation :
    • The @Transactional annotation in Spring (and JPA) is used to demarcate transactional boundaries around a method or a class.
    • It ensures that a method or a group of methods executes within a single transaction context, where either all operations succeed and are committed, or all operations fail and are rolled back.
    • This annotation helps in managing database transactions declaratively without explicitly handling EntityManager or Session transactions.
  • 2.  Key Features :
    • Transaction Management : @Transactional simplifies transaction management by handling transaction begin, commit, and rollback automatically.
    • Scope : It defines the scope of a single database transaction, ensuring data consistency and integrity.
    • Exception Handling : Automatically rolls back transactions on unchecked exceptions (runtime exceptions), ensuring data remains consistent in case of failures.

Transactional annotation in JPA

Example in Java

Here’s an example demonstrating the use of @Transactional in a Spring service class with Spring Data JPA:

Service Class (UserService.java)
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public void createUser(String username, String email) {
        // Creating a new user entity
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);

        // Saving the user entity using JpaRepository
        userRepository.save(user);

        // Additional operations within the same transaction
        // userRepository.delete(user); // Example of an operation that could be within the transaction scope
    }
}

Explanation of the Example

  • @Transactional : Applied to the createUser method, indicating that all operations within this method should be executed within a single transaction.
  • Database Operations : Within the createUser method, the userRepository.save(user) method persists the user entity to the database. If any operation within this method fails or throws an unchecked exception, the entire transaction will be rolled back, ensuring data consistency.
  • Transactional Scope : The createUser method ensures that the creation and saving of the user entity (User) are treated as atomic operations. If any exception occurs during the method execution, the transaction will roll back, ensuring that no incomplete or inconsistent data is left in the database.