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

Relationships

Entities that know each other.

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

In a real shop, data is connected. Every book has an author. An author can write many books. A book can have many tags. These connections are called relationships.

  • Data is connected
  • Books and authors
  • Relationships

Four kinds of relationship

One to one links one row to exactly one other, like a user, and their profile. Many to one links many rows to one, like many books to one author. One to many is the same link, seen from the other side. And many to many links many to many, like books and tags.

KindExample
One-to-oneuser ↔ profile
Many-to-onemany books → one author
One-to-manyone author → many books
Many-to-manybooks ↔ tags

Foreign keys

In the database, a relationship is a foreign key. The book table gets an author id column. It points to a row in the author table. So each book knows its author, by id.

tables.sqlsql
CREATE TABLE author (
    id    BIGINT PRIMARY KEY,
    name  VARCHAR(255)
);
CREATE TABLE book (
    id        BIGINT PRIMARY KEY,
    title     VARCHAR(255),
    author_id BIGINT REFERENCES author(id)
);

In JPA

In Java, we don't store ids. We store a reference to the other object. Book has an author field. Author has a list of books. And JPA turns those references into foreign keys, and joins, for us.

keyvalue
BookAuthor author;
AuthorList<Book> books;
Databaseauthor_id column
JPAreferences ↔ foreign keys

Summary

Relationships connect entities. In the database, they're foreign keys. In Java, they're references to other objects. Next, at Many To One.

Key takeaways
  • Foreign keys
  • Object references
  • 4 kinds
Next up: @ManyToOne — many books, one author