Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 66 ยท Projects

Project: Bookstore Orders Service

Build a bookstore orders service in Spring Boot: JPA model, Flyway schema, transactional order placement, safe stock updates, domain events and Testcontainers tests.

Most real back-end work is not a todo list. It is something like this: a customer buys three books, the stock of each book must go down, an order and its lines must be saved, and a confirmation must go out. If the second book is sold out, nothing may be saved at all. If two customers buy the last copy at the same moment, only one of them may get it. This project builds that service end to end, and it is the first one in the course where transactions, concurrency and events all meet in one use case.

Spring Boot, JPA, Flyway and Testcontainers cannot run on this site, so the real project code is shown in read-only blocks. Everything that carries the idea runs live: the schema and the order placement use the real H2 database through JDBC, and a second example races eight buyers for five copies. Each live example says what it stands in for. To build the real project, create it with the steps in Creating a Project and add the starters web, data-jpa, validation, flyway, postgresql and testcontainers.

What we are building

Catalog Books with a price and a stock level.
Orders An order has many lines, one per book.
Stock Selling reduces stock, never below zero.
Events A confirmed order announces itself.
1 / 2

The model

Four tables are enough. Customers are identified by email to keep the project small, and money is stored as integer cents because floating-point numbers and prices do not mix (see Bean Validation for how the incoming amounts are checked).

SQL
-- src/main/resources/db/migration/V1__create_shop.sql
create table book (
    id          bigint generated by default as identity primary key,
    isbn        varchar(20)  not null unique,
    title       varchar(200) not null,
    price_cents integer      not null check (price_cents >= 0),
    stock       integer      not null check (stock >= 0),
    version     bigint       not null default 0
);

create table orders (
    id             bigint generated by default as identity primary key,
    customer_email varchar(255) not null,
    total_cents    integer      not null,
    status         varchar(20)  not null,
    created_at     timestamp    not null default current_timestamp
);

create table order_line (
    id               bigint generated by default as identity primary key,
    order_id         bigint  not null references orders (id),
    book_id          bigint  not null references book (id),
    quantity         integer not null check (quantity > 0),
    unit_price_cents integer not null
);

Two details matter. check (stock >= 0) is a last line of defence: even a bug in the Java code cannot make stock negative, because the database refuses. And order_line stores unit_price_cents, a copy of the price at purchase time, so a later price change does not rewrite history. Flyway runs this script at startup; the details are in Database Migrations with Flyway, and Hibernate is set to ddl-auto: validate so the entities must match the script.

The entities mirror the tables. Keep them small and put the rules in the service:

Java
@Entity
public class Book {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String isbn;
    private String title;
    private int priceCents;
    private int stock;
    @Version
    private long version;
    // getters; no public setters for stock
}

@Entity
@Table(name = "orders")
public class CustomerOrder {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String customerEmail;
    private int totalCents;
    @Enumerated(EnumType.STRING)
    private OrderStatus status;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "order_id")
    private List<OrderLine> lines = new ArrayList<>();
    // constructor, addLine(...), getters
}

The class is called CustomerOrder because Order is a reserved word in SQL and a frequent source of confusing errors. The @Version field turns on optimistic locking, which comes up again below. Relationships and the N+1 trap are covered in Entity Relationships and the N+1 Problem.

Placing an order in one transaction

The use case is one method on a service, and it must be one transaction. Controllers stay thin: they validate the request body and call the service.

Java
public record PlaceOrderRequest(
        @Email @NotBlank String customerEmail,
        @NotEmpty List<@Valid Item> items) {

    public record Item(@NotNull Long bookId, @Min(1) @Max(50) int quantity) {}
}

@Service
public class OrderService {

    private final BookRepository books;
    private final OrderRepository orders;
    private final ApplicationEventPublisher events;

    public OrderService(BookRepository books, OrderRepository orders,
                        ApplicationEventPublisher events) {
        this.books = books;
        this.orders = orders;
        this.events = events;
    }

    @Transactional
    public CustomerOrder placeOrder(PlaceOrderRequest request) {
        var order = new CustomerOrder(request.customerEmail());
        for (var item : request.items()) {
            Book book = books.findById(item.bookId())
                    .orElseThrow(() -> new BookNotFoundException(item.bookId()));
            int updated = books.reserve(book.getId(), item.quantity());
            if (updated == 0) {
                throw new OutOfStockException(book.getId());
            }
            order.addLine(book.getId(), item.quantity(), book.getPriceCents());
        }
        orders.save(order);
        events.publishEvent(new OrderPlaced(order.getId(), order.getCustomerEmail(),
                order.getTotalCents()));
        return order;
    }
}

When OutOfStockException (a runtime exception) leaves the method, Spring rolls the transaction back, so the stock already taken from the first books returns. This is the default rollback rule explained in Transactions with @Transactional. A checked exception would not roll back unless you declare rollbackFor, which is a classic bug.

The reserve call is the heart of the concurrency story. A tempting version reads the book, checks book.getStock() >= quantity in Java, then writes the new value. Two requests can both read stock 1, both pass the check, and both sell the last copy. The safe version asks the database to check and change in a single statement:

Java
public interface BookRepository extends JpaRepository<Book, Long> {

    @Modifying
    @Query("""
            update Book b
               set b.stock = b.stock - :quantity
             where b.id = :id and b.stock >= :quantity
            """)
    int reserve(@Param("id") Long id, @Param("quantity") int quantity);
}

The return value is the number of rows changed: 1 means the copies were reserved, 0 means there was not enough stock. The database serializes concurrent updates of the same row, so exactly one buyer wins the last copy. (Optimistic locking with @Version is the alternative: both buyers load the row, and the second save fails with an OptimisticLockingFailureException that you retry. It suits rows that are rarely contended; for a hot stock counter, the guarded update is simpler and faster.)

Run the core logic

This example is the same use case in plain JDBC on real H2: one transaction, a guarded stock update, order lines with a price copy, a rollback when a line fails, and an event list that is filled after the commit. The placeOrder method is the stand-in for the @Transactional service; published stands in for the event publisher.

Java Transactional order placement on H2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the second order. Dune had already been taken out of stock when the Emma line failed, yet the final stock shows Dune unchanged and only one order exists. That is the rollback doing its job. Also note that only one event was published: the rolled-back order never announced itself.

Why events are published after the commit

events.publishEvent(...) inside the service looks like it notifies listeners immediately, and a plain @EventListener does exactly that, inside the transaction. If the listener sends an email and the commit then fails, the customer holds a confirmation for an order that does not exist. The fix is a listener bound to the transaction phase:

Java
@Component
public class OrderNotifications {

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void onOrderPlaced(OrderPlaced event) {
        // runs only if the order really committed
        mailService.sendConfirmation(event.email(), event.orderId());
    }
}

Two cautions: an AFTER_COMMIT listener runs outside the transaction, so a failure there does not roll anything back, and a database write inside it needs its own transaction (@Transactional(propagation = REQUIRES_NEW)). And if the process crashes between the commit and the listener, the notification is lost. The next project, Event-Driven Notifications, solves that with an outbox. For plain events see Application Events and Runners.

The race for the last copy

The second live example plays the scenario that makes the guarded update necessary: eight buyers, five copies, each buyer on its own connection and thread. The update ... where stock >= 1 statement decides each race in the database, so the numbers always add up, whatever the thread timing. The order in which buyers win may differ between runs, which is why the example prints only totals.

Java Eight buyers, five copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Whatever the interleaving, five buyers win, three are turned away, stock ends at zero and there are exactly five sales. The check (stock >= 0) constraint is never even needed, which is the point: the guarded update is correct on its own, and the constraint is the safety net. In the Boot service you translate the "0 rows updated" case into an HTTP 409 Conflict with a ProblemDetail, using the advice from Error Handling and Problem Details.

Testing with real PostgreSQL

H2 is perfect for quick examples, but your production database is PostgreSQL, with its own SQL dialect, locking behaviour and types. The most trustworthy test of this service runs against the same engine, and Testcontainers starts a throwaway PostgreSQL in Docker for the test run:

Java
@SpringBootTest
@Testcontainers
class OrderServiceIntegrationTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");

    @Autowired OrderService orders;
    @Autowired BookRepository books;

    @Test
    void failedLineRollsBackEarlierStockChanges() {
        var request = new PlaceOrderRequest("[email protected]", List.of(
                new PlaceOrderRequest.Item(1L, 1),
                new PlaceOrderRequest.Item(2L, 99)));

        assertThatThrownBy(() -> orders.placeOrder(request))
                .isInstanceOf(OutOfStockException.class);

        assertThat(books.findById(1L).orElseThrow().getStock()).isEqualTo(3);
    }
}

@ServiceConnection tells Boot to point the DataSource at the container, so no URL or password is configured by hand; the setup and CI notes are in Integration Tests with Testcontainers. Note that this test class is not annotated @Transactional: a test-managed transaction would roll back at the end and hide whether the service committed correctly. Add a second test with threads (like the live example above) to prove that overselling is impossible against the real database.

Extending the project

  • Add GET /orders/{id} and a paged GET /customers/{email}/orders, using a DTO projection instead of loading whole entities.
  • Add cancellation: set the order status to CANCELLED and return the stock in the same transaction.
  • Add an Idempotency-Key header so a client that retries a timed-out POST does not create a second order (see Designing a Clean API).
  • Add @Version handling to a price-update endpoint and return 409 on conflicting edits.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the stock update use update book set stock = stock - ? where id = ? and stock >= ? instead of reading the stock in Java first?

    A read-check-write sequence has a gap in which another request can change the row. The conditional update lets the database decide, and the affected-row count tells you whether the reservation worked.
  2. 2. A checked Exception is thrown from a @Transactional method with default settings. What happens to the transaction?

    By default only unchecked exceptions and errors trigger a rollback. Use runtime exceptions for business failures, or declare rollbackFor.
  3. 3. Why use @TransactionalEventListener(phase = AFTER_COMMIT) for the confirmation email?

    The listener runs after a successful commit, so rolled-back orders send nothing. It does not guarantee delivery: a crash after the commit loses the event, which is what an outbox fixes.
  4. 4. Why should the OrderServiceIntegrationTest above not be annotated @Transactional?

    A test-managed transaction wraps the service call, so the commit behaviour you want to verify never happens on its own.

Summary

  • Model orders with integer cents, a price copy on each line, database constraints as a safety net and Flyway for the schema.
  • Place an order in one @Transactional method; a runtime exception rolls everything back, including stock already taken.
  • Reserve stock with a guarded update ... where stock >= ? and check the affected-row count; this is correct under concurrency.
  • Publish events with @TransactionalEventListener(AFTER_COMMIT) so rolled-back orders announce nothing, and know that an outbox is needed for guaranteed delivery.
  • Test against the production database engine with Testcontainers, and do not wrap the test in a transaction.

Next: Project: Event-Driven Notifications.