Skip to lesson

@ManyToOne and @OneToMany

ShopLite shows "Mobiles" next to every phone. If Product stores only a category id, each screen needs a second repository call and glue code to find the name.

@ManyToOne: Product to Category

@ManyToOne maps a field that points at one other entity, where many rows of this table can point at the same row. With @JoinColumn(name = "category_id") it names the foreign key column that stores the link.

ShopLite shows the category name next to each phone. Product keeps a Category object, so product.getCategory().getName() is a single call.

Java
@ManyToOne(fetch = FetchType.LAZY)        // many products -> one category@JoinColumn(name = "category_id")          // the foreign key column in productsprivate Category category;

Example 1 · Product.java and ProductCategoryDemo.java: a lazy @ManyToOne

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Product.javaJava
package com.shoplite.lab.product;
import java.math.BigDecimal;
import com.shoplite.lab.category.Category;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.Table;
@Entity@Table(name = "products")public class Product {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "product_id")    private Integer id;
    private String sku;    private String name;
    @ManyToOne(fetch = FetchType.LAZY)        // many products -> one category    @JoinColumn(name = "category_id")          // the foreign key column in products    private Category category;
    private BigDecimal price;    private int stock;
    @Column(name = "is_active")    private boolean active;
    protected Product() {    }
    public Product(String sku, String name, Category category, BigDecimal price, int stock) {        this.sku = sku;        this.name = name;        this.category = category;        this.price = price;        this.stock = stock;        this.active = true;    }
    public Integer getId() { return id; }    public String getSku() { return sku; }    public String getName() { return name; }    public Category getCategory() { return category; }    public void setCategory(Category category) { this.category = category; }    public BigDecimal getPrice() { return price; }    public int getStock() { return stock; }    public boolean isActive() { return active; }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.product.Product;import com.shoplite.lab.product.ProductRepository;
@Component@Profile("product-category")class ProductCategoryDemo implements CommandLineRunner {
    private final ProductRepository products;
    ProductCategoryDemo(ProductRepository products) {        this.products = products;    }
    @Override    @Transactional(readOnly = true)   // keeps the session open, so the lazy category can load    public void run(String... args) {        Product phone = products.findById(1).orElseThrow();        System.out.println("Product: " + phone.getName());        System.out.println("Category id: " + phone.getCategory().getId());        System.out.println("Category name: " + phone.getCategory().getName());    }}
Output (--spring.profiles.active=product-category)
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
Product: Redmi Note 13 5G
Category id: 2
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Category name: Mobiles

What this code does

  • findById(1) sends one SELECT on products only. The category field holds a proxy: a stand-in object that knows only the id from category_id.
  • getCategory().getId() prints 2 with no SQL, because the proxy already has its id. The second SELECT runs at getName(), the first call that needs real data.
  • The Product constructor takes a Category, never an id; saving writes category.getId() into category_id.

A plain Integer categoryId field would need a second repository call in every service that shows the name. With the link, Hibernate also writes the right category_id when you save.

The field type is the entity, never the id; the column name goes only in @JoinColumn. The examples run in a small lab project: a Spring Boot 4.1 app with the JPA starter, the MySQL driver and the ShopLite database, with org.hibernate.SQL set to DEBUG so every statement is printed.

@OneToMany(mappedBy): Category to its products

@OneToMany(mappedBy) maps the collection side of a link: one category, many products. mappedBy names the field on the other entity that owns the link, so the list is read from that foreign key and adds no column. A link mapped from both sides is bidirectional.

A category can list its products. The list is read through products.category_id, so it needs no column of its own.

Example 2 · Category.java and CategoryProductsDemo.java: @OneToMany(mappedBy)

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Category.javaJava
package com.shoplite.lab.category;
import java.util.ArrayList;import java.util.List;
import com.shoplite.lab.product.Product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.OneToMany;import jakarta.persistence.OrderBy;import jakarta.persistence.Table;
@Entity@Table(name = "categories")public class Category {
    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Column(name = "category_id")    private Integer id;
    private String name;
    @ManyToOne(fetch = FetchType.LAZY)    @JoinColumn(name = "parent_id")             // NULL for a top-level category    private Category parent;
    @OneToMany(mappedBy = "parent")    @OrderBy("id")    private List<Category> children = new ArrayList<>();
    @OneToMany(mappedBy = "category")           // the other side of Product.category    @OrderBy("id")    private List<Product> products = new ArrayList<>();
    protected Category() {    }
    public Category(String name, Category parent) {        this.name = name;        this.parent = parent;    }
    public Integer getId() { return id; }    public String getName() { return name; }    public Category getParent() { return parent; }    public List<Category> getChildren() { return children; }    public List<Product> getProducts() { return products; }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.category.Category;import com.shoplite.lab.category.CategoryRepository;import com.shoplite.lab.product.Product;
@Component@Profile("category-products")class CategoryProductsDemo implements CommandLineRunner {
    private final CategoryRepository categories;
    CategoryProductsDemo(CategoryRepository categories) {        this.categories = categories;    }
    @Override    @Transactional(readOnly = true)    public void run(String... args) {        Category mobiles = categories.findById(2).orElseThrow();        System.out.println("Category: " + mobiles.getName());        for (Product p : mobiles.getProducts()) {          // first use loads the list            System.out.println("  " + p.getSku() + "  " + p.getName() + "  " + p.getPrice());        }        System.out.println("Count: " + mobiles.getProducts().size());    }}
Output (--spring.profiles.active=category-products)
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Category: Mobiles
DEBUG SQL - select p1_0.category_id,p1_0.product_id,p1_0.is_active,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=? order by p1_0.product_id
  MOB-RN13  Redmi Note 13 5G  17999.00
  MOB-GM35  Samsung Galaxy M35  19999.00
  MOB-IP15  iPhone 15 128GB  69900.00
Count: 3

What this code does

  • mappedBy = "category" points at the category field in Product; the list has no column of its own and is read through products.category_id.
  • The products SELECT runs only when the loop starts, and @OrderBy("id") becomes order by p1_0.product_id.
  • size() after the loop sends nothing: the list is already loaded. This class also has the self-reference used in Example 4.

Hibernate loads the list with one SELECT ... WHERE category_id = ? the first time you use it. That is fine for Mobiles with 3 products, and a trap for a category with 20,000: touching the list loads every one of them into memory.

Add a @OneToMany only when you work with the children through the parent, as an order works with its items. When you only need the products of category 2, a repository query with paging is better, and Category needs no list at all; ShopLite's project keeps Category without a products list for exactly this reason. A link mapped from one side only is called unidirectional.

Default fetch types: always set LAZY on @ManyToOne

Fetch type says when Hibernate loads a linked entity. FetchType.LAZY loads it the first time you use it; FetchType.EAGER loads it at once with its owner, every time. The JPA defaults are EAGER for @ManyToOne and @OneToOne, and LAZY for @OneToMany and @ManyToMany.

A page lists 15 products and never shows a category. With the default @ManyToOne, does Hibernate still load the categories? Run findAll() both ways and count the statements.

Example 3 · FindAllDemo.java: findAll() with the EAGER default, then with LAZY

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

Java
package com.shoplite.lab;
import java.util.List;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.product.Product;import com.shoplite.lab.product.ProductRepository;
@Component@Profile("find-all")class FindAllDemo implements CommandLineRunner {
    private final ProductRepository products;
    FindAllDemo(ProductRepository products) {        this.products = products;    }
    @Override    @Transactional(readOnly = true)    public void run(String... args) {        List<Product> all = products.findAll();       // we never touch getCategory()        System.out.println("Loaded " + all.size() + " products");    }}
// Run 1: Product.category mapped as plain @ManyToOne (the default, EAGER)// Run 2: Product.category mapped as @ManyToOne(fetch = FetchType.LAZY), as in Example 1
Output (--spring.profiles.active=find-all)
--- Run 1: @ManyToOne (EAGER by default)
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
Loaded 15 products
--- Run 2: @ManyToOne(fetch = FetchType.LAZY)
DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0
Loaded 15 products
--- Run 1 again, but findById(1) instead of findAll()
DEBUG SQL - select p1_0.product_id,p1_0.is_active,c1_0.category_id,c1_0.name,c1_0.parent_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 left join categories c1_0 on c1_0.category_id=p1_0.category_id where p1_0.product_id=?

What this code does

  • With EAGER, the code never touches a category, yet Hibernate sends 6 extra SELECTs, one for each category used by the 15 products (2 to 7). That is the N+1 problem: 1 + 6 queries.
  • With LAZY, the same findAll() is one SELECT. Nothing is loaded that nobody asked for.
  • For findById, EAGER adds a left join categories to the single select. Every query for products pays for the category, wanted or not, which is why LAZY is the rule.

EAGER cannot be switched off for one query. A plain findAll() on 15 products must also load every category, one extra SELECT per distinct category, so 1 query becomes 7. One query plus N more for the links is the N+1 problem; the Performance Traps module measures and fixes it.

The rule for this course: write fetch = FetchType.LAZY on every @ManyToOne and @OneToOne. When one screen needs the category too, load it on purpose with a query for that case, as the ShopLite project does with a fetch join.

Predict the output

Count the SELECTs

ShopLite has 15 products in 6 categories. How many SELECTs does each call send?

Round 1 of 3

findAll() with the default @ManyToOne, categories never used.

@Entity
class Product {
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
}
List<Product> all = products.findAll();
Lazy loading needs an open session (a database connection owned by Hibernate). The lab demos run inside @Transactional methods so the session stays open; the Persistence Context and Transactions modules explain what happens when it is closed.

A self-reference: parent and children

A self-reference is a relationship from an entity to its own type. Category.parent is a @ManyToOne to another Category, and children is the @OneToMany(mappedBy = "parent") list that mirrors it.

ShopLite's categories.parent_id points at another category: Mobiles, Laptops and Accessories sit under Electronics.

Example 4 · CategoryTreeDemo.java: walking parent and children

Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)

CategoryRepository.javaJava
// src/main/java/com/shoplite/lab/category/CategoryRepository.javapackage com.shoplite.lab.category;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CategoryRepository extends JpaRepository<Category, Integer> {
    List<Category> findByParentIsNullOrderById();}
// src/main/java/com/shoplite/lab/CategoryTreeDemo.javapackage com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.category.Category;import com.shoplite.lab.category.CategoryRepository;
@Component@Profile("tree")class CategoryTreeDemo implements CommandLineRunner {
    private final CategoryRepository categories;
    CategoryTreeDemo(CategoryRepository categories) {        this.categories = categories;    }
    @Override    @Transactional(readOnly = true)    public void run(String... args) {        for (Category top : categories.findByParentIsNullOrderById()) {            System.out.println(top.getName());            for (Category child : top.getChildren()) {                System.out.println("  - " + child.getName() + " (parent: " + child.getParent().getName() + ")");            }        }    }}
Output (--spring.profiles.active=tree)
DEBUG SQL - select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.parent_id is null order by c1_0.category_id
Electronics
DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? order by c1_0.category_id
  - Mobiles (parent: Electronics)
  - Laptops (parent: Electronics)
  - Accessories (parent: Electronics)
Books
DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? order by c1_0.category_id
Fashion
DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? order by c1_0.category_id
Home & Kitchen
DEBUG SQL - select c1_0.parent_id,c1_0.category_id,c1_0.name from categories c1_0 where c1_0.parent_id=? order by c1_0.category_id

What this code does

  • findByParentIsNullOrderById is a derived query: where c1_0.parent_id is null. These are the four top-level categories.
  • Each getChildren() sends one SELECT ... where parent_id=?, even for Books, Fashion and Home & Kitchen, which have no children: 1 + 4 queries for 7 rows.
  • child.getParent().getName() sends nothing: the parent is already loaded in this session, so Hibernate reuses that object.

Nothing new is needed: the same pair of annotations as Product and Category, with both ends on one class. parent_id is nullable, so top-level categories simply have parent == null.

Walking a tree through getChildren() sends one SELECT for every category you open. With 7 categories that is harmless; with 500 it is slow, so the ShopLite project builds its category tree from one SELECT of all categories.

Collections: List or Set, always initialised

An entity collection is a List or Set field that holds the many side of a relationship, such as List<Product> products. Start it with an empty collection; Hibernate swaps in its own lazy one when it loads the entity.

A category created with new has no products yet. The plain-Java program below shows why its list must start empty, not null.

Example 5 · Why every collection starts as an empty list

CollectionInitDemo.javaJava
import java.util.ArrayList;import java.util.List;
class Product {    final String name;
    Product(String name) {        this.name = name;    }}
// Without an initial value the field is null until someone assigns a listclass CategoryWithoutInit {    private List<Product> products;
    List<Product> getProducts() {        return products;    }}
// The habit for every entity collection: start with an empty listclass CategoryWithInit {    private List<Product> products = new ArrayList<>();
    List<Product> getProducts() {        return products;    }}
public class CollectionInitDemo {    public static void main(String[] args) {        CategoryWithInit watches = new CategoryWithInit();        watches.getProducts().add(new Product("Noise ColorFit Pro 5"));        System.out.println("With an empty list: " + watches.getProducts().size() + " product");
        CategoryWithoutInit gadgets = new CategoryWithoutInit();        try {            gadgets.getProducts().add(new Product("boAt Wave Call"));        } catch (NullPointerException e) {            System.out.println("Without it: " + e.getMessage());        }    }}
Output
With an empty list: 1 product
Without it: Cannot invoke "java.util.List.add(Object)" because the return value of "CategoryWithoutInit.getProducts()" is null

What this code does

  • This plain-Java program shows what happens to a new entity object before Hibernate ever sees it: a field without = new ArrayList<>() is null.
  • The helpful NullPointerException message (Java 14 and later) names the exact call that returned null.
  • With the empty list, code such as a helper method can always call add, for new and loaded objects alike.

Write every entity collection as private List<Product> products = new ArrayList<>();. For objects loaded from the database, Hibernate replaces it with its own collection (a PersistentBag for a List, a PersistentSet for a Set) that loads lazily. Never give a collection a setter that replaces the whole list: Hibernate tracks changes inside the collection object it gave you, so change the contents instead.

Choose the type:

  • List (Hibernate calls an unordered List a bag) keeps insertion order, allows duplicates, and @OrderBy("id") sorts it when loaded. It is the default choice for @OneToMany.
  • Set allows no duplicates, but calls equals and hashCode on your entities, so they must be written safely (the Entities and Mapping module covers that). It is the better choice for @ManyToMany, as the next lessons show.

Next step

Check your understanding

12 quick questions