Spring / Spring Boot 4 Basics Interview Questions
What is Spring Boot's transaction management with @Transactional?
Spring Boot 4 auto-configures transaction management when a data source is on the classpath. The @Transactional annotation declaratively wraps methods in a database transaction, with Spring AOP managing commit and rollback.
// Service with transaction management: @Service public class OrderService { private final OrderRepository orderRepo; private final InventoryRepository inventoryRepo; private final EventPublisher events; // Default: propagation=REQUIRED, isolation=DEFAULT, rollbackFor=RuntimeException @Transactional public Order placeOrder(CreateOrderRequest request) { // All operations in one transaction: Order order = orderRepo.save(new Order(request)); inventoryRepo.reserveStock(request.productId(), request.quantity()); events.publish(new OrderPlacedEvent(order.getId())); return order; // Commits on successful return // Rolls back on RuntimeException } // Read-only transaction (performance optimisation): @Transactional(readOnly = true) public Optional<Order> findById(String id) { return orderRepo.findById(id); // Hibernate skips dirty checking for read-only transactions } // Custom rollback rules: @Transactional(rollbackFor = {BusinessException.class, IOException.class}) public void processPayment(String orderId) throws IOException { // Rolls back on checked IOException too } // Propagation types: @Transactional(propagation = Propagation.REQUIRES_NEW) public void auditLog(String message) { // Always runs in its own NEW transaction, // suspending any existing outer transaction auditRepo.save(new AuditEntry(message)); } }
| Propagation | Behaviour |
|---|---|
| REQUIRED (default) | Join existing transaction; create new if none |
| REQUIRES_NEW | Always create a new transaction; suspend existing |
| SUPPORTS | Join existing if present; run non-transactional if none |
| NOT_SUPPORTED | Run non-transactional; suspend existing |
| NEVER | Must run non-transactionally; error if transaction exists |
| MANDATORY | Must join existing; error if no transaction exists |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
