Transactions
All or nothing.
Imagine taking money from one account, then the app crashes, before adding it to the other. The money vanishes. Transactions stop that from happening.
- Two steps
- A crash in between
- Data goes wrong
What a transaction is
A transaction groups several database changes into one unit. Either all of them happen, or none of them do. If anything fails, the database rolls back, and undoes the changes. This is called commit, or rollback.
| key | value |
|---|---|
| Transaction | one unit of work |
| Success | commit: keep all changes |
| Failure | rollback: undo all changes |
| Rule | all or nothing |
StockService.java
Both methods save a book, and then fail with an exception. The first has no transaction. The second has at Transactional. So if it fails, Spring rolls back everything it did.
@Service
public class StockService {
private final BookRepository books;
public StockService(BookRepository books) { this.books = books; }
public void addWithoutTransaction() {
books.save(new Book("Book A", "Someone", 5));
throw new IllegalStateException("Failed after saving Book A");
}
@Transactional
public void addInTransaction() {
books.save(new Book("Book B", "Someone", 5));
throw new IllegalStateException("Failed after saving Book B");
}
}Rollback in action
The runner counts the books, then calls each method, catching the failures. After each one, it counts again. Run it. We start with eight books. Without a transaction, book A was saved before the failure, so we have nine. With at Transactional, book B was rolled back, so we still have nine.
@Component
public class TxDemo implements CommandLineRunner {
private final StockService stock;
private final BookRepository books;
public TxDemo(StockService s, BookRepository b) { stock = s; books = b; }
@Override
public void run(String... args) {
System.out.println("Books at start: " + books.count());
try { stock.addWithoutTransaction(); }
catch (RuntimeException e) { System.out.println(e.getMessage()); }
System.out.println("After the first method: " + books.count());
try { stock.addInTransaction(); }
catch (RuntimeException e) { System.out.println(e.getMessage()); }
System.out.println("After the second method: " + books.count());
}
}Books at start: 8 Failed after saving Book A After the first method: 9 Failed after saving Book B After the second method: 9
Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private double price;
protected Book() {}
public Book(String title, String author, double price) {
this.title = title; this.author = author; this.price = price;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }
}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
}Also uses StockService.java
@Service
public class StockService {
private final BookRepository books;
public StockService(BookRepository books) { this.books = books; }
public void addWithoutTransaction() {
books.save(new Book("Book A", "Someone", 5));
throw new IllegalStateException("Failed after saving Book A");
}
@Transactional
public void addInTransaction() {
books.save(new Book("Book B", "Someone", 5));
throw new IllegalStateException("Failed after saving Book B");
}
}Also uses data.sql
INSERT INTO book (title, author, price) VALUES
('Dune', 'Frank Herbert', 9.99),
('The Hobbit', 'J.R.R. Tolkien', 8.99),
('Circe', 'Madeline Miller', 10.99),
('Children of Dune', 'Frank Herbert', 8.49),
('Song of Achilles', 'Madeline Miller', 9.49),
('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
('Emma', 'Jane Austen', 6.99),
('Persuasion', 'Jane Austen', 7.49);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueWhere to put @Transactional
Put at Transactional on service methods that change data. By default, it rolls back for runtime exceptions. Repository methods like save already run in their own transaction. And read only equals true, can speed up methods that only read.
| key | value |
|---|---|
| Put it on | service methods |
| Rolls back for | runtime exceptions |
| save() | already transactional |
| readOnly = true | for read-only methods |
Summary
A transaction is all or nothing. At Transactional on a service method rolls back every change if it fails. Next, some practice.
Key takeaways- All or nothing
- @Transactional
- Rollback on failure