#379 Transaction Rollback When Catching an Exception

Companies:
Sberbank
Themes:
SpringTransactionsCode Review

What happens when the it() method is called if an error occurs:

  1. In insert()?
  2. In update()?
@Service
class Service {
    @Autowired
    private AccountRepository repository;

    public void it(Data data) {

        try {
            repository.doIt(data);
        } catch (Exception e) {
            // Log the error
            System.err.println("Error in service method: " + e.getMessage());
            // Additional error handling if necessary
        }
    }
}

@Repository
class AccountRepository {

    @Transactional
    public void doIt(Data data) throws Exception {
        try {
            insert();
            update();
        } catch (Exception e) {
            // Log the error
            System.err.println("Error during transaction: " + e.getMessage());
            throw e; // Rethrow the exception
        }
    }

    private void insert() {
        // Data insertion logic
    }

    private void update() {
        // Data update logic
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in