Performance: Transaction management with @Transactional
This affects backend transaction handling speed and resource locking, indirectly impacting frontend responsiveness and user experience.
Jump into concepts and practice - no test required
@Transactional
public void updateData() {
repository.save(entity1);
repository.save(entity2);
// atomic commit or rollback
}public void updateData() {
// multiple DB calls without @Transactional
repository.save(entity1);
repository.save(entity2);
// no rollback on failure
}| Pattern | DB Operations | Locks Held | Response Delay | Verdict |
|---|---|---|---|---|
| No @Transactional with multiple DB calls | Multiple separate calls | Longer lock duration | Higher delay due to multiple commits | [X] Bad |
| Single @Transactional wrapping DB calls | Single atomic call | Shorter lock duration | Lower delay with one commit | [OK] Good |
@Transactional in a Spring Boot application?@Transactional to a method in a Spring Boot service class?@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?@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?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.