AI Hints
Home›Spring Boot Tutorial›Relationships, @ManyToOne and @OneToMany
Spring Boot · Lesson 66 of 120

@OneToMany

One author, many books.

⏱ 2 min read▶ Video at 1:29:01🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Now let's look from the other side. One author has many books. We want to ask an author, which books did you write?

  • The other side
  • One author, many books
  • Which books?

Author with books

At One To Many gives the author a list of books. Mapped by author means, the book's author field owns this relationship. So no new column is added. The list just reads books whose author id matches. We start it as an empty list.

Author.javajava
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

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

    protected Author() {}
    public Author(String name) { this.name = name; }
    // getters follow, including getBooks()
}

The owning side

Only one side stores the foreign key, and that's the owning side. With many to one, and one to many, the many side owns it. So book dot author is what gets saved. The author's list is mapped by that field, and is read only, in practice.

keyvalue
Owning sideBook.author (@ManyToOne)
Inverse sideAuthor.books (mappedBy)
Savedonly the owning side
Tipalways set book.author

Each author's books

The runner loads all authors, and lists each one's book titles. At Transactional keeps the database connection open, while we read the lists. We'll see why that matters, in the lesson on lazy loading. Run it. Each author lists their own books.

RelDemo.javajava
@Component
public class RelDemo implements CommandLineRunner {
    private final AuthorRepository authors;
    public RelDemo(AuthorRepository authors) { this.authors = authors; }

    @Override
    @Transactional
    public void run(String... args) {
        for (Author a : authors.findAll()) {
            List<String> titles = a.getBooks().stream().map(Book::getTitle).toList();
            System.out.println(a.getName() + ": " + titles);
        }
    }
}
Output
Frank Herbert: [Dune, Children of Dune]
J.R.R. Tolkien: [The Hobbit]
Madeline Miller: [Circe, Song of Achilles]
Also uses Author.java
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

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

    protected Author() {}
    public Author(String name) { this.name = name; }

    public Long getId() { return id; }
    public String getName() { return name; }
    public List<Book> getBooks() { return books; }
}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private double price;

    @ManyToOne
    private Author author;

    protected Book() {}
    public Book(String title, double price, Author author) {
        this.title = title; this.price = price; this.author = author;
    }

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public double getPrice() { return price; }
    public Author getAuthor() { return author; }
}
Also uses AuthorRepository.java
public interface AuthorRepository extends JpaRepository<Author, Long> {}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}
Also uses data.sql
INSERT INTO author (name) VALUES ('Frank Herbert'), ('J.R.R. Tolkien'), ('Madeline Miller');
INSERT INTO book (title, price, author_id) VALUES
  ('Dune', 9.99, 1), ('Children of Dune', 8.49, 1),
  ('The Hobbit', 8.99, 2), ('Circe', 10.99, 3), ('Song of Achilles', 9.49, 3);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true

Summary

At One To Many, with mapped by, gives the inverse side a list. The many side, book dot author, owns the relationship. Next, lazy loading.

Key takeaways
  • @OneToMany(mappedBy)
  • Owning side: Book
  • List<Book> books
Next up: Lazy Loading — load only when needed