$npx -y skills add rrezartprebreza/spring-boot-skills --skill transactional-patternsUse when working with @Transactional, multi-step database operations, distributed transactions, or any code that needs atomicity guarantees. Covers propagation rules, isolation levels, read-only optimization, and common pitfalls.
| 1 | # Transactional Patterns |
| 2 | |
| 3 | ## Basic Rules |
| 4 | |
| 5 | - `@Transactional` belongs on **service methods**, never controllers or repositories |
| 6 | - Default propagation is `REQUIRED` — joins existing transaction or creates one |
| 7 | - Always use on methods that write to the DB or coordinate multiple writes |
| 8 | - `@Transactional(readOnly = true)` on all read-only service methods — enables optimizations |
| 9 | |
| 10 | ```java |
| 11 | @Service |
| 12 | @RequiredArgsConstructor |
| 13 | @Transactional(readOnly = true) // default for all methods in this service |
| 14 | public class OrderService { |
| 15 | |
| 16 | @Transactional // overrides readOnly for writes |
| 17 | public Order createOrder(CreateOrderRequest request) { |
| 18 | inventoryService.reserve(request.items()); // participates in same TX |
| 19 | return orderRepository.save(Order.from(request)); |
| 20 | } |
| 21 | |
| 22 | public Optional<Order> findById(UUID id) { |
| 23 | return orderRepository.findById(id); // readOnly = true inherited |
| 24 | } |
| 25 | } |
| 26 | ``` |
| 27 | |
| 28 | ## Propagation |
| 29 | |
| 30 | | Propagation | Behavior | |
| 31 | |-------------|----------| |
| 32 | | `REQUIRED` (default) | Join existing TX or create new | |
| 33 | | `REQUIRES_NEW` | Always create new TX, suspend existing | |
| 34 | | `SUPPORTS` | Join if exists, proceed without TX if not | |
| 35 | | `NOT_SUPPORTED` | Always run without TX | |
| 36 | | `MANDATORY` | Must have existing TX, throw if not | |
| 37 | | `NEVER` | Must NOT have TX, throw if one exists | |
| 38 | |
| 39 | ```java |
| 40 | // REQUIRES_NEW — for audit logging that must survive rollback |
| 41 | @Transactional(propagation = Propagation.REQUIRES_NEW) |
| 42 | public void logAuditEvent(AuditEvent event) { |
| 43 | auditRepository.save(event); // commits independently of parent TX |
| 44 | } |
| 45 | |
| 46 | // Order TX rolls back, audit log still saved |
| 47 | @Transactional |
| 48 | public void processOrder(Order order) { |
| 49 | auditService.logAuditEvent(new AuditEvent("ORDER_START", order.getId())); |
| 50 | try { |
| 51 | // ... process, may throw |
| 52 | } catch (Exception e) { |
| 53 | auditService.logAuditEvent(new AuditEvent("ORDER_FAILED", order.getId())); |
| 54 | throw e; // parent TX rolls back, audit TX already committed |
| 55 | } |
| 56 | } |
| 57 | ``` |
| 58 | |
| 59 | ## Self-Invocation Pitfall |
| 60 | |
| 61 | ```java |
| 62 | // ❌ BROKEN — self-invocation bypasses Spring proxy, @Transactional ignored |
| 63 | @Service |
| 64 | public class OrderService { |
| 65 | @Transactional |
| 66 | public void processAll(List<UUID> ids) { |
| 67 | ids.forEach(id -> this.processSingle(id)); // bypasses proxy! |
| 68 | } |
| 69 | |
| 70 | @Transactional(propagation = Propagation.REQUIRES_NEW) |
| 71 | public void processSingle(UUID id) { ... } // never creates new TX |
| 72 | } |
| 73 | |
| 74 | // ✅ FIX — inject self or extract to separate bean |
| 75 | @Service |
| 76 | @RequiredArgsConstructor |
| 77 | public class OrderService { |
| 78 | private final OrderProcessor orderProcessor; // separate bean |
| 79 | |
| 80 | @Transactional |
| 81 | public void processAll(List<UUID> ids) { |
| 82 | ids.forEach(id -> orderProcessor.processSingle(id)); // goes through proxy |
| 83 | } |
| 84 | } |
| 85 | ``` |
| 86 | |
| 87 | ## Handling Exceptions |
| 88 | |
| 89 | ```java |
| 90 | // @Transactional rolls back on RuntimeException by default |
| 91 | // For checked exceptions, explicitly declare rollbackFor |
| 92 | |
| 93 | @Transactional(rollbackFor = InsufficientInventoryException.class) // checked exception |
| 94 | public Order createOrder(CreateOrderRequest request) throws InsufficientInventoryException { |
| 95 | ... |
| 96 | } |
| 97 | |
| 98 | // noRollbackFor — for non-fatal exceptions you want to commit anyway |
| 99 | @Transactional(noRollbackFor = OptimisticLockException.class) |
| 100 | public void updateWithRetry(UUID id) { ... } |
| 101 | ``` |
| 102 | |
| 103 | ## Optimistic Locking |
| 104 | |
| 105 | ```java |
| 106 | @Entity |
| 107 | public class Order { |
| 108 | @Version |
| 109 | private Long version; // Hibernate handles conflicts automatically |
| 110 | } |
| 111 | |
| 112 | // Handles concurrent updates |
| 113 | @Transactional |
| 114 | public Order updateStatus(UUID id, OrderStatus newStatus) { |
| 115 | Order order = orderRepository.findById(id).orElseThrow(); |
| 116 | order.updateStatus(newStatus); // if another TX modified it, throws ObjectOptimisticLockingFailureException |
| 117 | return orderRepository.save(order); |
| 118 | } |
| 119 | ``` |
| 120 | |
| 121 | ## Distributed Transactions (Saga Pattern) |
| 122 | |
| 123 | For multi-service operations, use the Saga pattern instead of distributed TX: |
| 124 | |
| 125 | ```java |
| 126 | @Service |
| 127 | @RequiredArgsConstructor |
| 128 | public class OrderSaga { |
| 129 | |
| 130 | @Transactional |
| 131 | public void execute(CreateOrderRequest request) { |
| 132 | Order order = orderRepository.save(Order.create(request)); |
| 133 | try { |
| 134 | inventoryClient.reserve(request.items()); // step 1 |
| 135 | paymentClient.charge(order.getId(), request.total()); // step 2 |
| 136 | order.confirm(); |
| 137 | orderRepository.save(order); |
| 138 | } catch (PaymentException e) { |
| 139 | inventoryClient.release(request.items()); // compensate step 1 |
| 140 | order.fail("Payment failed"); |
| 141 | orderRepository.save(order); |
| 142 | throw e; |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | ``` |
| 147 | |
| 148 | ## Side Effects After Commit |
| 149 | |
| 150 | Never fire an external side effect (email, Kafka publish, webhook, cache warm) inside the transaction — |
| 151 | if the TX rolls back, you've already sent it |