Why this matters
- Without transactions, a BookStore order that deducts inventory and creates an order record can leave inconsistent data if the second step fails.
- Propagation and isolation levels determine how nested service calls interact — wrong settings cause subtle bugs.
@Transactionalonly works on Spring-managed beans called through the proxy — self-invocation bypasses it.
@Transactional basics
L1 · FresherWrap service methods that write data so failures roll back the unit of work — default propagation is REQUIRED.
Rollback rules
L2 · IntermediateUnchecked exceptions roll back by default; checked exceptions do not unless you set rollbackFor.
Propagation levels
L3 · AdvancedREQUIRES_NEW suspends the outer transaction for audit logs; NEVER fails if a transaction already exists.
Self-invocation trap
L4 · ExpertCalling @Transactional methods from the same class bypasses the proxy — extract to another bean or use TransactionTemplate.
Basic usage
// learn:fragment
@Service
public class OrderService {
private final BookRepository bookRepository;
private final OrderRepository orderRepository;
@Transactional
public Order placeOrder(Long bookId, int quantity) {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));
if (book.getStock() < quantity) {
throw new InsufficientStockException(bookId, quantity);
}
book.setStock(book.getStock() - quantity);
bookRepository.save(book);
Order order = new Order(book, quantity);
return orderRepository.save(order);
}
}
If orderRepository.save() fails, the stock deduction rolls back automatically.
Read-only transactions
// learn:fragment
@Service
@Transactional(readOnly = true)
public class BookService {
public List<Book> findAll() {
return repository.findAll();
}
@Transactional // overrides class-level readOnly for writes
public Book create(CreateBookRequest request) {
return repository.save(new Book(...));
}
}
readOnly = true hints Hibernate to skip dirty checking and can route to read replicas.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 7 sections
- Propagation levels
- REQUIRES_NEW example
- Rollback rules
- Isolation levels
- What each anomaly looks like
- Programmatic transactions
- Transaction boundaries in BookStore
Test yourself
Answer these before moving on — recall is what makes it stick.