Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท Associations and Inheritance

Many-to-One and One-to-Many

Map the most common association: @ManyToOne with a foreign key, bidirectional @OneToMany with mappedBy, helper methods that keep both sides in sync, and the join-column pitfalls.

Most real data is connected: a book has an author, an order has many lines. In the database this is a foreign key. In Java it is an object reference or a collection. Hibernate maps one to the other. The association you will use ninety percent of the time is many-to-one (the foreign key side) together with its mirror image one-to-many.

Real Hibernate code in this lesson is read-only; runnable programs are plain-Java stand-ins with real JDBC.

Many-to-one: the foreign key

Java
@Entity
public class Book {
    @Id @GeneratedValue
    private Long id;
    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;
}

The book table gets an author_id column. Many books point to one author. Note fetch = FetchType.LAZY: the default for @ManyToOne is eager, which loads the author with every book and is a classic cause of the N+1 problem. Set LAZY explicitly on every to-one association and fetch eagerly only in queries that need it.

This one-directional mapping is often all you need. To list an author's books you can query from Book b where b.author = :author.

One-to-many: the other direction

Java
@Entity
public class Author {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author")
    private List<Book> books = new ArrayList<>();
}

mappedBy = "author" says: this side is the inverse side; the foreign key belongs to the author field of Book. There is no books column and no extra table. Only the side without mappedBy (the owning side, here Book.author) is used by Hibernate to write the foreign key.

flowchart LR
    A["Author<br/>books: List of Book (inverse, mappedBy)"] -->|"1 to many"| B["Book<br/>author: Author (owning, has author_id)"]
    B -->|"many to 1"| A

The foreign key lives in the book table; the owning side is the one that writes it.

Keep both sides in sync

Hibernate persists only what the owning side says. If you add a book to author.getBooks() but never set book.setAuthor(author), nothing is saved, yet your Java objects look consistent until the next load. Put the synchronization in helper methods on the parent:

Java
public void addBook(Book book) {
    books.add(book);
    book.setAuthor(this);
}

public void removeBook(Book book) {
    books.remove(book);
    book.setAuthor(null);
}

Always call addBook instead of touching the list directly, and expose the collection as read-only (Collections.unmodifiableList) if you can.

Unidirectional one-to-many: avoid

A @OneToMany without mappedBy and without @JoinColumn creates an extra join table and extra statements. With @JoinColumn(name = "author_id") it uses the foreign key but issues an INSERT followed by an UPDATE for every child. A bidirectional mapping with mappedBy, or just a @ManyToOne, is simpler and faster.

Common mistakes

  • Leaving @ManyToOne eager.
  • Using mappedBy with the wrong field name (it must be the field name on the other entity, not a column).
  • Forgetting the helper methods, so one side is out of sync.
  • Putting @Data or a Lombok toString/hashCode on both sides, which recurses forever (author.books.author...). Exclude the association from toString, equals and hashCode.

Stand-in: the foreign key is the only truth

Java Stand-in: owning side writes the foreign key

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.

The second book was in the author's list, yet its author_id is null in the database. That is exactly what happens in Hibernate when you only update the mappedBy side.

Stand-in: lazy to-one in action

Java Stand-in: a lazy reference loads on first use

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which side of a bidirectional one-to-many/many-to-one writes the foreign key?

    The owning side is the one without mappedBy; the inverse side is ignored when writing.
  2. 2. What is the default fetch type of @ManyToOne, and what should you usually set?

    To-one associations default to EAGER; explicit LAZY avoids unwanted loads and N+1 problems.
  3. 3. What does mappedBy = "author" refer to?

    mappedBy takes the field name of the owning side.
  4. 4. Why add helper methods like addBook to the parent?

    Only the owning side is persisted, so both sides must be updated together.

Summary

  • @ManyToOne with @JoinColumn is the foreign key and the owning side.
  • @OneToMany(mappedBy = ...) is the inverse side and writes nothing.
  • Set every to-one association to FetchType.LAZY explicitly.
  • Use helper methods to keep both sides in sync; avoid unidirectional @OneToMany.
  • Exclude associations from toString, equals and hashCode.
  • Here, real Hibernate code is read-only; the runnable programs are plain-Java stand-ins.

Next: One-to-One Mapping