Sobes.tech
Junior — Middle

What is the purpose of the @Transactional annotation in database operations?

sobes.tech AI

Answer from AI

The @Transactional annotation in Java is used to designate a method or class in which database operations should be executed within a single transaction. This guarantees that all changes are either successfully applied together or rolled back in case of an error, maintaining data integrity.

Example:

@Transactional
public void updateUserData(User user) {
    userRepository.save(user);
    // other database operations
}

If an exception occurs in the method, all changes will be automatically rolled back.