Transaction management helps keep your data safe and consistent. The @Transactional annotation makes sure a group of actions either all happen or none happen.
Transaction management with @Transactional in Spring Boot
@Transactional
public void methodName() {
// database operations
}Place @Transactional above methods or classes to manage transactions.
By default, if an exception occurs, the transaction rolls back.
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}@Transactional(readOnly = true)
public User findUser(Long id) {
return userRepository.findById(id).orElse(null);
}@Transactional(rollbackFor = Exception.class)
public void updateData() throws Exception {
// multiple database updates
}This service simulates a money transfer. If the amount is over 1000, it throws an error and rolls back the transaction, so no changes happen.
import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service public class BankService { private List<String> transactions = new ArrayList<>(); @Transactional public void transferMoney(String fromAccount, String toAccount, int amount) { transactions.add("Withdraw " + amount + " from " + fromAccount); if (amount > 1000) { throw new RuntimeException("Amount too large, rollback transaction"); } transactions.add("Deposit " + amount + " to " + toAccount); } public List<String> getTransactions() { return transactions; } }
Use @Transactional on public methods only for it to work properly.
By default, only unchecked exceptions (RuntimeException) cause rollback.
Transactions help keep your data safe when multiple steps must all succeed together.
@Transactional groups database actions so they all succeed or fail together.
It helps keep data consistent and safe from partial changes.
Use it on methods that do multiple related database operations.
Practice
@Transactional in a Spring Boot application?Solution
Step 1: Understand the role of @Transactional
@Transactional groups multiple database operations so they succeed or fail together.Step 2: Identify the effect on data consistency
If any operation fails, all changes are rolled back to keep data correct.Final Answer:
To ensure multiple database operations are executed as a single unit and rollback on failure -> Option AQuick Check:
@Transactional = atomic database actions [OK]
- Confusing @Transactional with caching or logging
- Thinking it speeds up queries
- Assuming it auto-generates schema
@Transactional to a method in a Spring Boot service class?Solution
Step 1: Recall correct annotation placement
Annotations like @Transactional go before the method signature.Step 2: Check each option's syntax
@Transactional public void updateData() { ... } places @Transactional correctly before the method declaration.Final Answer:
@Transactional public void updateData() { ... } -> Option AQuick Check:
Annotation before method = correct syntax [OK]
- Placing annotation inside method body
- Putting annotation after method signature
- Using annotation as a modifier keyword
@Transactional:
@Transactional
public void saveUserAndAccount(User user, Account account) {
userRepository.save(user);
accountRepository.save(account);
if(account.getBalance() < 0) {
throw new RuntimeException("Negative balance not allowed");
}
}
What happens if account.getBalance() < 0 is true during execution?Solution
Step 1: Understand rollback behavior of @Transactional
By default, RuntimeExceptions cause the transaction to rollback all changes.Step 2: Analyze the exception thrown
The method throws RuntimeException if balance is negative, triggering rollback.Final Answer:
Neither user nor account is saved; transaction rolls back -> Option DQuick Check:
RuntimeException triggers rollback = no data saved [OK]
- Assuming partial saves happen
- Thinking only last save rolls back
- Ignoring exception effect on transaction
@Transactional
public void updateRecords() {
recordRepository.updateA();
recordRepository.updateB();
// Missing exception handling
}
If updateB() throws a checked exception (not RuntimeException), what will happen to the transaction?Solution
Step 1: Recall default rollback rules of @Transactional
By default, only unchecked exceptions (RuntimeException) cause rollback.Step 2: Analyze checked exception behavior
Checked exceptions do not trigger rollback unless configured or rethrown as RuntimeException.Final Answer:
Transaction will commit despite the exception -> Option BQuick Check:
Checked exceptions do not rollback by default [OK]
- Assuming all exceptions cause rollback
- Not knowing difference between checked and unchecked exceptions
- Expecting rollback without configuration
public void outerMethod() {
innerMethod();
}
@Transactional
public void innerMethod() {
// database updates
if(someCondition) throw new RuntimeException();
}
If outerMethod() is called, will the transaction rollback if innerMethod() throws the exception? Assume default proxy-based Spring transaction management.Solution
Step 1: Understand Spring proxy behavior for @Transactional
Spring uses proxies, so self-invocation (method calling another in same class) bypasses proxy and ignores @Transactional.Step 2: Analyze effect on transaction rollback
Since outerMethod calls innerMethod directly, @Transactional on innerMethod is ignored, so no transaction starts and no rollback occurs.Final Answer:
No, transaction does not rollback because outerMethod is not @Transactional and calls innerMethod internally -> Option CQuick Check:
Self-call bypasses @Transactional proxy = no rollback [OK]
- Assuming @Transactional always works on internal calls
- Thinking RuntimeException always triggers rollback here
- Not knowing Spring proxy limitations
Ready to prove it?
Pass the test and this pattern moves unknown
