← Learning Hub
Intermediate

Relationships, Transactions and Paging

Real data is connected - orders have lines, lines have products. JPA maps these relationships, and transactions make multi-step changes all-or-nothing, so an order is never half-saved.

One order has many order lines

Example
@Entity
@Table(name = "orders")
public class Order {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String customerEmail;
    private int total;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    public void addLine(OrderLine line) { lines.add(line); line.setOrder(this); }
    // getters and setters ...
}

@Entity
public class OrderLine {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @ManyToOne(fetch = FetchType.LAZY) private Order order;
    @ManyToOne(fetch = FetchType.LAZY) private Product product;
    private int qty;
    private int price;          // price at the time of ordering
    // constructor, getters and setters ...
}

@Transactional: all or nothing

Placing an order must reduce stock and save the order. If anything fails halfway, nothing should be saved. @Transactional does exactly that: if the method throws, every change is rolled back.

Example
@Service
public class OrderService {
    private final ProductRepository products;
    private final OrderRepository orders;

    public OrderService(ProductRepository products, OrderRepository orders) {
        this.products = products; this.orders = orders;
    }

    @Transactional
    public Order place(String email, Map<Long, Integer> items) {
        Order order = new Order();
        order.setCustomerEmail(email);
        int total = 0;
        for (var item : items.entrySet()) {
            Product p = products.findById(item.getKey())
                .orElseThrow(() -> new NotFoundException("Product " + item.getKey() + " not found"));
            if (p.getStock() < item.getValue()) {
                throw new OutOfStockException("Only " + p.getStock() + " " + p.getName() + " left");
            }
            p.setStock(p.getStock() - item.getValue());     // saved automatically at the end
            order.addLine(new OrderLine(p, item.getValue(), p.getPrice()));
            total += p.getPrice() * item.getValue();
        }
        order.setTotal(total);
        return orders.save(order);
    }
}

Inside a transaction, changes to loaded entities (like setStock) are saved automatically when the method finishes.

Paging and sorting

Example
// GET /api/products?page=0&size=20&sort=price,asc
@GetMapping
public Page<Product> list(Pageable pageable) {
    return repo.findAll(pageable);
}

Spring reads page, size and sort from the URL. Never return a whole big table in one reply.

Watch out for the N+1 problem: loading 100 orders and then each order's lines one by one makes 101 queries. Turn on spring.jpa.show-sql=true to spot it, and fix it with a fetch join (@Query("select o from Order o join fetch o.lines")) or @EntityGraph.
Key points
  • @OneToMany / @ManyToOne map relationships.
  • @Transactional makes changes all-or-nothing.
  • Page results and watch for the N+1 problem.

📝 Test yourself

1. What does @Transactional do if the method throws an exception?
2. Which annotation goes on the 'many' side pointing to its order?
3. Fill in the parameter type that reads page, size and sort:
public Page<Product> list( pageable)