Sobes.tech
Junior — Middle

How can a transaction rollback mechanism be implemented in case of a checked exception?

sobes.tech AI

Answer from AI

In Java, to implement a transaction rollback mechanism when a checked exception occurs, the @Transactional annotation with the rollbackFor parameter is usually used. By default, transactions are rolled back only for unchecked exceptions (RuntimeException and Error), but it is possible to explicitly specify which checked exceptions should trigger a rollback.

Example:

@Transactional(rollbackFor = {MyCheckedException.class})
public void someMethod() throws MyCheckedException {
    // business logic
    if (someCondition) {
        throw new MyCheckedException("Error");
    }
}

In this example, if MyCheckedException is thrown, the transaction will be rolled back.