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

@ManyToOne

Many books, one author.

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

Let's give every book an author. Many books can share the same author, so from the book's side, it's many to one.

  • Every book has an author
  • Many share one
  • Many-to-one

Book with an author

The author field holds an Author object. At Many To One says, many books point to one author. JPA stores it as an author id column. And our constructor now takes the author too.

Book.javajava
@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;
    }
    // getters follow, including getAuthor()
}

The tables and a join

The database starts with three authors, and five books. Show SQL is on. The runner loads book one, and prints its author's name. Run it. Hibernate created the author table, and the book table, with an author id column, and a foreign key. Loading the book also joined the author table, so the name is ready.

RelDemo.javajava
@Component
public class RelDemo implements CommandLineRunner {
    private final AuthorRepository authors;
    private final BookRepository books;
    public RelDemo(AuthorRepository a, BookRepository b) { authors = a; books = b; }

    @Override
    public void run(String... args) {
        Book dune = books.findById(1L).orElseThrow();
        System.out.println(dune.getTitle() + " by " + dune.getAuthor().getName());
    }
}
Output
Hibernate: create table author (id bigint generated by default as identity, name
varchar(255), primary key (id))
Hibernate: create table book (price float(53) not null, author_id bigint, id bigint
generated by default as identity, title varchar(255), primary key (id))
Hibernate: alter table if exists book add constraint FKklnrv3weler2ftkweewlky958 foreign
key (author_id) references author
Hibernate: select b1_0.id,a1_0.id,a1_0.name,b1_0.price,b1_0.title from book b1_0 left
join author a1_0 on a1_0.id=b1_0.author_id where b1_0.id=?
Dune by Frank Herbert
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
spring.jpa.show-sql=true
Also uses _log
own

Summary

At Many To One links many books to one author, stored as an author id column with a foreign key. Next, at One To Many, the other side.

Key takeaways
  • @ManyToOne
  • author_id column
  • Foreign key
Next up: @OneToMany — one author, many books