Skip to content
notes.vinhnq.com

Search

SpringSenior20 min read

Cart and checkout with Spring: the model, the transaction and never overselling

Review 17 cards
On this page

Spring MVC end to end series: 1. Maven and project layout · 2. DispatcherServlet and views · 3. Forms and validation · 4. Form login with Spring Security · 5. Sessions and remember-me · 6. File upload · 7. Cart and checkout · 8. Pagination and dynamic filters

A shopping cart looks simple, yet it’s where a shop most easily loses money: wrong totals, selling more than is in stock, two orders from one double click. This post builds the cart and checkout module with Spring Boot 3 and JPA and fixes the bugs that show up in a typical beginner version. Afterwards you can design the data model and write an order placement that stays correct when many people buy at once.

1. The data model: cart, order and price snapshots

Key idea: the cart holds references to products (the price is always the current price); the order holds copies of the name and price at order time. They look alike but play different roles.

erDiagram
  USERS ||--o| CART : "has at most 1"
  CART ||--|{ CART_ITEM : "contains"
  PRODUCT ||--o{ CART_ITEM : "added as"
  USERS ||--o{ ORDERS : "places"
  ORDERS ||--|{ ORDER_LINE : "contains"
  PRODUCT ||--o{ ORDER_LINE : "bought as"
  CART_ITEM {
    bigint cart_id
    bigint product_id
    int quantity
  }
  ORDER_LINE {
    bigint order_id
    string product_name
    decimal unit_price
    int quantity
  }
  ORDERS {
    bigint user_id
    string request_id
    decimal total
    string status
  }
Table Key constraint Why
cart user_id unique one cart per user (one-to-one)
cart_item unique (cart_id, product_id) one line per product in a cart
orders unique (user_id, request_id) no two orders from one click
order_line product_name, unit_price not null the snapshot used for invoices and reconciliation

The beginner version keeps a price column on the cart line. That price goes stale the moment an admin changes it, and the customer sees one price but pays another. The cart should keep only quantities; the price comes from the product when displayed and is frozen at checkout. For @OneToOne, @OneToMany(mappedBy) and the owning side, see the post on JPA relationships.

Code: Cart, CartItem, ShopOrder, OrderLine entities
@Entity
public class Cart {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    @OneToOne(optional = false) @JoinColumn(name = "user_id", unique = true) private AppUser user;
    @OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<CartItem> items = new ArrayList<>();

    public void add(Product product, int quantity) {
        if (quantity <= 0) throw new IllegalArgumentException("quantity must be > 0");
        for (CartItem item : items)
            if (item.getProduct().getId().equals(product.getId())) { item.increase(quantity); return; }
        items.add(new CartItem(this, product, quantity));
    }
    public void remove(Long itemId) { items.removeIf(i -> i.getId().equals(itemId)); }
    public void clear() { items.clear(); }
    public int totalQuantity() { return items.stream().mapToInt(CartItem::getQuantity).sum(); }
}

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"cart_id", "product_id"}))
public class CartItem { /* id, @ManyToOne cart (LAZY), @ManyToOne product, int quantity */ }

@Entity
@Table(name = "orders", uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "request_id"}))
public class ShopOrder {
    // id, user (LAZY), requestId, total, status = PENDING, receiver*, createdAt
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<OrderLine> lines = new ArrayList<>();
    public void addLine(Product p, int qty) {
        OrderLine line = new OrderLine(this, p, qty);   // snapshots p.getName(), p.getPrice()
        lines.add(line);
        total = total.add(line.lineTotal());
    }
    public void changeStatus(OrderStatus next) {
        if (!status.canMoveTo(next)) throw new IllegalStateException(status + " -> " + next + " is not allowed");
        status = next;
    }
}

orphanRemoval = true: removing a line from the list makes Hibernate delete that row, so cart.remove(id) and cart.clear() need no CartItem repository. The beginner version has to “delete the cart details first, then the cart” because of the foreign key; here the cart is never deleted, it just becomes empty.

2. Adding to the cart: merge lines inside the entity

Key idea: the “is this product already in the cart?” logic lives in Cart.add, not scattered across controllers. The number on the cart icon is totalQuantity(), computed from the lines.

The add-to-cart request sends only productId and quantity (default 1). The user id comes from the logged-in principal, not from the form: trusting a client-sent userId lets anyone add items to someone else’s cart. The service runs in one transaction: find the cart (create it if missing), load the product, call cart.add.

@Transactional
public int add(Long userId, Long productId, int qty) {
    Cart cart = carts.findByUserId(userId).orElseGet(() -> carts.save(new Cart(users.getReferenceById(userId))));
    Product p = products.findById(productId).orElseThrow(() -> new NotFoundException("product " + productId));
    cart.add(p, qty);
    return cart.totalQuantity();
}

No save at the end: cart is a managed entity, so Hibernate detects the change (dirty checking) and flushes it on commit.

Removing a line: a form POSTs to /cart/items/{itemId}/delete with the CSRF token. The service loads the current user’s cart and calls cart.remove(itemId), so an itemId from someone else’s cart deletes nothing. The beginner version looks up the cart detail by the posted id and deletes it directly, so anyone who guesses an id can delete another user’s line (IDOR, insecure direct object reference: accessing an object by id without checking ownership).

Adding to the cart with AJAX (no page reload) still needs the CSRF token, this time in a header. Thymeleaf prints the token into meta tags, and JavaScript reads them and adds them to fetch; CSRF details are in part 4.

const token = document.querySelector('meta[name="_csrf"]').content;
const header = document.querySelector('meta[name="_csrf_header"]').content;
await fetch('/cart/items', { method: 'POST', headers: { [header]: token },
                             body: new URLSearchParams({ productId: 42, quantity: 1 }) });

3. Cart in the session or in the database

Key idea: a database cart survives across devices and logins; a session cart is light and works for guests. Real shops usually combine them: guests use the session or a cookie, and on login the guest cart is merged into the database cart.

Whichever you pick, the session should hold only an id or a few small numbers, never a JPA entity. An entity in the session is detached, lazy loading breaks, and it must be Serializable if the session is stored in Redis or JDBC.

4. Money: BigDecimal and a total computed from the lines

Key idea: prices and totals use BigDecimal with DECIMAL columns; the order total is the sum of unitPrice × quantity over the lines, computed in a single method (ShopOrder.addLine).

The beginner version uses double for prices and has a bug where the stored order total is wrong: the summing loop forgot the quantity and was later fixed to sum += price * quantity. The bug came from computing the total in the service, away from where the lines are created. When the total is added inside addLine, there’s no way to create a line and forget its amount.

5. Placing the order in one transaction

Key idea: placing an order is four steps that must succeed together: duplicate check, stock decrement, order creation, cart cleanup. Put all four in one @Transactional, and decrement stock with a single conditional UPDATE so two people can’t both buy the last item.

sequenceDiagram
    participant U as Browser
    participant C as CartController
    participant S as OrderService
    participant D as Database
    U->>C: POST /orders (requestId, receiver)
    C->>S: placeOrder(userId, form)
    S->>D: find order by (user_id, request_id)
    alt already exists
        S-->>C: return the existing order
    else new
        S->>D: UPDATE product SET stock = stock - q WHERE id = ? AND stock >= q
        Note over S,D: 0 rows updated means out of stock, throw and roll back
        S->>D: INSERT orders, order_line
        S->>D: DELETE cart_item
    end
    C-->>U: 302 /orders/thanks

Three decisions in this flow:

  • requestId: a UUID generated when the checkout page opens, sent in a hidden input. Clicking “Place order” twice sends the same requestId twice; the second request finds the existing order and returns it. The unique (user_id, request_id) catches two requests running at exactly the same time. The full theory is in the post on idempotency.
  • Atomic stock decrement: UPDATE ... WHERE stock >= :qty lets the database check and subtract in one step, locking the row while it does. Zero rows updated means not enough stock. The beginner version doesn’t decrement stock at all (the author admits it’s missing).
  • Rollback: throwing OutOfStockException (unchecked) makes Spring roll back the whole transaction: stock from earlier lines is restored, no order is created, the cart stays intact.

After placing the order, the controller redirects to a thank-you page (Post/Redirect/Get, see part 2), so F5 doesn’t resubmit the form.

Code: OrderService, the stock query and the order tests
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
    @Modifying(flushAutomatically = true)
    @Query("update Product p set p.stock = p.stock - :qty where p.id = :id and p.stock >= :qty")
    int decreaseStock(@Param("id") Long id, @Param("qty") int qty);
}

@Service
public class OrderService {
    @Transactional
    public ShopOrder placeOrder(Long userId, CheckoutForm form) {
        var existing = orders.findByUserIdAndRequestId(userId, form.requestId());
        if (existing.isPresent()) return existing.get();

        Cart cart = carts.findByUserId(userId).orElseThrow(() -> new NotFoundException("cart"));
        if (cart.getItems().isEmpty()) throw new IllegalStateException("cart is empty");

        ShopOrder order = new ShopOrder(users.getReferenceById(userId), form.requestId(),
                form.receiverName(), form.receiverAddress(), form.receiverPhone());
        for (CartItem item : cart.getItems()) {
            if (products.decreaseStock(item.getProduct().getId(), item.getQuantity()) == 0)
                throw new OutOfStockException(item.getProduct().getName());
            order.addLine(item.getProduct(), item.getQuantity());
        }
        cart.clear();
        return orders.save(order);
    }
}

The SQL Hibernate generates for the stock query (H2):

update product p1_0 set stock=(p1_0.stock-cast(? as integer)) where p1_0.id=? and p1_0.stock>=?

The tests (Spring Boot 3.5, H2, JDK 21, run with mvn test, all green):

Test What it checks
placeOrderSnapshotsPriceDecrementsStockAndIsIdempotent 2 MacBooks at 25M + 1 Dell at 12M: total 62M, Mac stock 5 → 3, cart back to 0; a second call with the same requestId returns the same id, only 1 order
outOfStockRollsBackEverything cart with 1 Mac and 2 Asus (Asus stock 1): throws OutOfStockException, Mac stock still 5, cart still 3 items, 0 orders
twoBuyersRaceForLastItem two threads order the last item, released together by a CountDownLatch: exactly one ok, one out, stock 0
checkoutFormValidated blank name, bad phone: re-renders cart/checkout with field errors

The race test is correct because of the database (the row lock taken by the update), not because of thread ordering.

6. Order status, the admin page and order history

Key idea: order status is a small state machine: each status may move only to a few next ones. The admin page paginates over orders without fetching lines; a user’s history page loads orders and lines in one query.

stateDiagram-v2
    [*] --> PENDING
    PENDING --> CONFIRMED
    PENDING --> CANCELLED
    CONFIRMED --> SHIPPING
    CONFIRMED --> CANCELLED
    SHIPPING --> DELIVERED
    DELIVERED --> [*]
    CANCELLED --> [*]

OrderStatus.canMoveTo(next) is a switch over the enum; ShopOrder.changeStatus throws on an invalid move. Even an admin picking from a dropdown can’t push a delivered order back to “pending”. Cancelling an order that already took stock must give the stock back in the same transaction. Admins don’t create orders for customers; the detail page only reads the order and its lines.

A user’s history: @EntityGraph(attributePaths = "lines") on findByUserIdOrderByIdDesc makes Hibernate generate one query with left join order_line, instead of 1 query for orders plus N for lines (N+1, see the N+1 post). With spring.jpa.open-in-view=false, a view touching order.lines without that graph throws LazyInitializationException; the test historyLoadsLinesOutsideTransaction checks exactly that.

Exercises

Lab: the cart and checkout module. On a Spring MVC app that already has users, products and login (earlier parts), build:

  1. Add a product to the cart (default quantity 1); adding the same product again increases the quantity. Show the item count on the cart icon, including for users who never had a cart (show 0).
  2. Remove a line from the cart; change quantities on the checkout page before confirming (quantity 0 removes the line).
  3. A checkout page for the receiver’s name, address and phone; placing the order creates a PENDING order with the right total, decrements stock, empties the cart and redirects to a thank-you page.
  4. Admin: a paginated order list, a detail view, status changes that follow the rules. User: purchase history.

Correctness requirements: clicking “Place order” twice yields one order; when two people buy the last item exactly one succeeds; when stock runs out nothing changes.

Solution: the rest of the lab and what a senior would add

Parts 1 and 3 are in sections 2 and 5. Changing quantities (this snippet was not run; the lab has only add and remove):

// Cart
public void changeQuantity(Long itemId, int quantity) {
    if (quantity < 0) throw new IllegalArgumentException("quantity must be >= 0");
    if (quantity == 0) { remove(itemId); return; }
    items.stream().filter(i -> i.getId().equals(itemId)).findFirst()
         .orElseThrow(() -> new NotFoundException("item " + itemId)).setQuantity(quantity);
}

The controller receives a list of (itemId, quantity) from the checkout form and applies it in one transaction before the confirmation step. Checking quantity <= stock here only warns the customer early; the real guarantee is still the UPDATE at order time.

The order controller, handling two parallel requests:

@PostMapping("/orders")
String place(@AuthenticationPrincipal ShopUserDetails me, @Valid @ModelAttribute("form") CheckoutForm form,
             BindingResult result, RedirectAttributes ra) {
    if (result.hasErrors()) return "cart/checkout";
    ShopOrder order;
    try { order = orders.placeOrder(me.id(), form); }
    catch (DataIntegrityViolationException dup) {          // a parallel request created the order first
        order = orderRepo.findByUserIdAndRequestId(me.id(), form.requestId()).orElseThrow();
    }
    ra.addFlashAttribute("orderId", order.getId());
    return "redirect:/orders/thanks";
}

(The catch branch isn’t in the lab and wasn’t run.) Admin page: Page<ShopOrder> findByStatus(OrderStatus, Pageable) without a graph.

A senior would also add:

  • Outbox: send the confirmation email and call logistics through an outbox table written in the same transaction, not API calls inside placeOrder (call out, then roll back, and the email is already gone).
  • Online payment: a PENDING_PAYMENT order holds stock for a limited time, and a job releases it on expiry; IPN and reconciliation in the VNPay post.
  • Price at checkout time: if the price changes between viewing the cart and clicking order, show it again for confirmation instead of silently charging the new price.
  • Lock ordering when using FOR UPDATE across products, and a per-line quantity cap (stop someone ordering 10,000 units to hoard stock).
  • Status audit: an order_status_history table (who changed what, when) rather than just overwriting status.

Remember

  • Explain why an order line snapshots name and price but a cart line doesn’t.
  • Write the order placement: check requestId, decrement stock with a conditional UPDATE, create the order, empty the cart, all in one transaction.
  • Know why not to store a total-quantity column and not to compute money with double.
  • Name the two JPA traps in this module: clearAutomatically detaching the cart, and paginating with a collection fetch.
  • Know when the cart belongs in the session vs the database, and how to merge carts on login.

Interview questions

Junior

Why must an order line store the product’s price and name instead of just product_id?

Because an order is a record of one moment: later changes to a product’s price or name must not change orders already placed.

With only product_id, an admin raising the price tomorrow would “raise” the total of every old order, breaking invoices and reconciliation. Keep product_id for analytics, but name and unit price are copies.

What goes wrong if you name an entity Order?

The table order collides with the SQL keyword ORDER, so select ... from order is a syntax error.

Fix it with @Table(name = "orders"). Don’t enable global quoting for one table.

Mid

A customer clicks “Place order” twice. How do you make sure only one order is created?

Give the form an idempotency key (a requestId generated when checkout opens), check it inside the order transaction, and add a unique constraint on (user_id, request_id) as a safety net.

Disabling the button in JavaScript only lowers the odds (slow network, retries, two tabs). The second request finds the existing order and returns it. If both run in parallel, the loser hits the unique constraint; catch it and read the order back.

Why not store the number of items in the cart as its own column?

Because it’s derived from the lines; storing it separately means keeping it in sync on every code path, and sooner or later it drifts.

Computing it on demand is fast enough for a few dozen lines. If you really need a cached column, update it in the same transaction as the line change, in a single method of the aggregate.

Would you keep the cart in HttpSession or in the database?

The database for logged-in users (durable, works across devices); the session or an anonymous cookie for guests, merged into the database cart on login.

The session should hold ids, not JPA entities: entities get detached, lazy loading breaks, and they must be serializable when Spring Session stores them in Redis or JDBC.

Senior

Two people buy the last unit at the same time. How does your design avoid overselling?

Decrement stock with UPDATE product SET stock = stock - :q WHERE id = :id AND stock >= :q inside the order transaction; zero rows updated means throw and roll back the whole order.

The database locks the row during the update, so the two statements run one after the other on that row and the second sees stock = 0 and changes nothing. Reading stock in Java and calling save is a lost update. When the rule doesn’t fit a WHERE clause, use @Version with retry, or FOR UPDATE with locks taken in id order. A test with two threads released together proves it.

A @Transactional method runs a bulk update and then modifies an entity it loaded earlier, but the change is never saved. Why?

The bulk update is declared @Modifying(clearAutomatically = true): it clears the persistence context, the loaded entity becomes detached, and dirty checking no longer sees its changes.

There’s no exception, just no SQL. Fix: drop clearAutomatically (keep flushAutomatically so earlier changes are flushed before the bulk statement), reload the entity after the bulk statement, or run the bulk update last. Write tests that check database state after the method, not just its return value.

The admin order list is paginated and must show each order’s line count. How do you write the query?

Paginate over orders without fetching the collection, then get the line counts with one aggregate group by order_id query for that page’s ids (or a count subquery in a projection).

A fetch join or entity graph on a collection combined with Pageable makes Hibernate load the whole result into memory and slice it there (warning HHH90003004). For one user’s history, unpaginated or small, a single-query entity graph is fine.

Useful phrases for interviews

  • “The cart references products; the order snapshots name and price at checkout.”
  • “Merging duplicate products belongs inside the cart aggregate, backed by a unique constraint.”
  • “The cart count is a derived value, so I compute it instead of storing it.”
  • “Placing an order is one transaction: idempotency check, stock decrement, order insert, cart cleanup.”
  • “A conditional update returns zero rows when stock is short, and that triggers a rollback.”
  • “The form carries an idempotency key, so a double click still creates one order.”
  • “clearAutomatically detached my cart, so the later changes were silently dropped.”
  • “Paginating with a collection fetch makes Hibernate page in memory, so I page over the parent only.”
  • “Order status is a small state machine with explicit allowed transitions.”

Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.