Sobes.tech
Senior

How does the @Transactional annotation work in Spring?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring is used for managing database transactions. When a method is marked with this annotation, Spring automatically starts a transaction before executing the method and completes it afterward.

If the method executes successfully, the transaction is committed — all changes are saved to the database. If an exception occurs during execution (usually a RuntimeException), the transaction is rolled back — all changes are undone.

This ensures data integrity without the need to manually write code for beginning, committing, and rolling back transactions.

Example:

@Transactional
public void saveUser(User user) {
    userRepository.save(user);
    // if an exception is thrown here, changes will not be saved
}