@Transactional. If this method throws a RuntimeException, what will be the outcome regarding the transaction?public void updateData() {
// some database operations
if(someCondition) {
throw new RuntimeException("Error occurred");
}
}By default, Spring rolls back transactions when a RuntimeException or Error is thrown inside a @Transactional method. Checked exceptions do not trigger rollback unless configured.
IOException occurs. Which annotation usage is correct?The rollbackFor attribute specifies exceptions that should trigger rollback, including checked exceptions like IOException. Other options are invalid attributes.
@Transactional throws a checked exception, but the transaction commits instead of rolling back. What is the most likely cause?public void process() throws IOException {
// database update
throw new IOException("Checked exception");
}Spring only rolls back transactions automatically for unchecked exceptions (RuntimeException and Error) by default. Checked exceptions require explicit rollback configuration.
@Transactional method is called from another method within the same class, what happens to the transaction behavior?Spring uses proxies to apply transactions. Internal calls within the same class bypass the proxy, so @Transactional is ignored in that case.
outerMethod() annotated with @Transactional(propagation = Propagation.REQUIRED) and innerMethod() annotated with @Transactional(propagation = Propagation.REQUIRES_NEW). If innerMethod() throws a RuntimeException but outerMethod() catches it and completes normally, what is the final state of the database?public void outerMethod() {
try {
innerMethod();
} catch (RuntimeException e) {
// handle exception
}
// continue with other DB operations
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void innerMethod() {
// DB insert
throw new RuntimeException("Fail");
}Propagation.REQUIRES_NEW starts a new transaction. When innerMethod throws an exception, its transaction rolls back. The outer transaction continues and commits normally.