Relationships, paging and migrations
Real data models have relationships (customers have orders, orders have items), real tables hold too many rows to return at once, and real schemas change over time. This lesson covers JPA relationships and the N+1 problem, pagination and sorting with Spring Data, and versioned database migrations with Flyway.
Migrations with Flyway
In production, the schema must change in a controlled, repeatable way, not by Hibernate guessing (ddl-auto=update). Flyway runs versioned SQL scripts in order and records which ones it has applied. Add spring-boot-starter-flyway and put scripts in src/main/resources/db/migration:
-- V1__create_catalog.sql
CREATE TABLE product (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL,
category VARCHAR(50) NOT NULL
);
INSERT INTO product (name, price, category) VALUES
('Laptop', 899.00, 'electronics'), ('Headphones', 59.99, 'electronics'),
('Mug', 8.99, 'kitchen'), ('Teapot', 34.50, 'kitchen'), ('Kettle', 45.00, 'kitchen'),
('Notebook', 4.50, 'office'), ('Desk lamp', 29.00, 'office');-- V2__create_orders.sql
CREATE TABLE customer (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(200) NOT NULL UNIQUE
);
CREATE TABLE orders (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customer (id),
status VARCHAR(20) NOT NULL
);
CREATE TABLE order_item (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders (id),
product_id BIGINT NOT NULL REFERENCES product (id),
quantity INTEGER NOT NULL CHECK (quantity > 0)
);At startup, Flyway applies anything new:
Creating Schema History table "PUBLIC"."flyway_schema_history" ... Migrating schema "PUBLIC" to version "1 - create catalog" Migrating schema "PUBLIC" to version "2 - create orders" Successfully applied 2 migrations to schema "PUBLIC", now at version v2
Rules: never edit a migration that has already run anywhere (Flyway checks checksums and refuses to start); add a new V3__… instead. With Flyway present, Spring Boot stops Hibernate from creating tables; set spring.jpa.hibernate.ddl-auto=validate so Hibernate checks your entities match the schema. (Liquibase is a popular alternative with the same idea.)
Relationships
@Entity
@Table(name = "orders") // "order" is a reserved word in SQL
public class Order {
public enum Status { PAID, SHIPPED, CANCELLED }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Customer customer; // the customer_id foreign key
@Enumerated(EnumType.STRING)
private Status status;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
…
}
@Entity
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Order order;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Product product;
private int quantity;
…
}| Annotation | Relationship | Example |
|---|---|---|
@ManyToOne |
Many of this belong to one of that | Order → Customer |
@OneToMany(mappedBy = …) |
The other side of a many-to-one | Order → its items |
@OneToOne |
Exactly one each | User → Profile |
@ManyToMany |
Many to many, through a join table | Product ↔ Tag |
- The side with the foreign key column (
@ManyToOne) owns the relationship;mappedBymarks the other side. cascade = ALL+orphanRemoval = true: saving an order saves its items; removing an item from the list deletes its row.- Make
@ManyToOnelazy (FetchType.LAZY). Its default is eager, which loads related rows even when you don't need them.
The N+1 problem
Listing 50 orders and touching order.getCustomer().getName() and each order's items triggers one query for the orders, plus more queries per order: N+1 queries, the most common JPA performance bug. Fix it by fetching what you need in the same query, with an entity graph (or a join fetch query):
public interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = {"customer", "items", "items.product"})
List<Order> findWithDetailsByCustomerEmail(String email);
}With logging.level.org.hibernate.SQL=debug, the log shows a single query with joins for the whole page of orders (shortened):
select o1_0.id,o1_0.customer_id,c2_0.id,c2_0.email,c2_0.name,i1_0.order_id,i1_0.id,i1_0.product_id,p1_0.id,p1_0.category,p1_0.name,p1_0.price,i1_0.quantity,o1_0.status from orders o1_0 join customer c1_0 on c1_0.id=o1_0.customer_id join customer c2_0 on c2_0.id=o1_0.customer_id left join …
Two more tools: DTO projections (select new com.example.OrderSummary(o.id, c.name) from Order o join o.customer c) fetch only the columns you need, and spring.jpa.properties.hibernate.default_batch_fetch_size=50 loads lazy collections in batches instead of one by one.
Pagination and sorting
Spring Data understands Pageable: page number, page size and sort order, read straight from query parameters (?page=1&size=20&sort=price,desc):
public interface ProductRepository extends JpaRepository<Product, Long> {
Page<Product> findByCategory(String category, Pageable pageable);
}
@RestController
@RequestMapping("/api/products")
public class CatalogController {
record ProductView(Long id, String name, BigDecimal price) {}
private final ProductRepository products;
public CatalogController(ProductRepository products) {
this.products = products;
}
@GetMapping
public PagedModel<ProductView> list(@RequestParam(required = false) String category,
@PageableDefault(size = 3, sort = "price", direction = Sort.Direction.ASC) Pageable pageable) {
Page<Product> page = category == null ? products.findAll(pageable) : products.findByCategory(category, pageable);
return new PagedModel<>(page.map(p -> new ProductView(p.getId(), p.getName(), p.getPrice())));
}
}curl localhost:8080/api/products
curl "localhost:8080/api/products?page=1"
curl "localhost:8080/api/products?category=kitchen&sort=name,desc&size=2"{"content":[{"id":6,"name":"Notebook","price":4.50},{"id":3,"name":"Mug","price":8.99},{"id":7,"name":"Desk lamp","price":29.00}],"page":{"size":3,"number":0,"totalElements":7,"totalPages":3}}
{"content":[{"id":4,"name":"Teapot","price":34.50},{"id":5,"name":"Kettle","price":45.00},{"id":2,"name":"Headphones","price":59.99}],"page":{"size":3,"number":1,"totalElements":7,"totalPages":3}}
{"content":[{"id":4,"name":"Teapot","price":34.50},{"id":3,"name":"Mug","price":8.99}],"page":{"size":2,"number":0,"totalElements":3,"totalPages":2}}- Pages are numbered from 0.
Pageruns an extracountquery for the totals; return aSliceinstead when you only need "is there a next page?".PagedModelgives a stable JSON shape (content+page); don't serialisePageobjects directly.- Limit the maximum size:
spring.data.web.pageable.max-page-size=100. - For very deep pages, prefer keyset/cursor pagination (Spring Data's
ScrollPositionandWindow), as covered in the APIs track.
Practice
- Write
V3__add_product_stock.sqlthat adds astock INTEGER NOT NULL DEFAULT 0column, and add the field to the entity. - Add
GET /api/customers/{id}/orders?page=0returning a page of that customer's orders, newest first. - Write a JPQL query that returns each customer's name and number of orders as a record.
1.A migration has already been applied in production and you need to change the table again. What do you do?
2.What causes the N+1 problem?
3.In Spring Data, what is the first page number?