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
@Entitypublic 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()}
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.
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
@Componentpublic 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
@Entitypublic 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
@Entitypublic 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);