AI Hints
Home›Spring Boot Tutorial›Lazy Loading, Cascade and Many to Many
Spring Boot · Lesson 69 of 120

Many to Many

Books and tags.

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

A book can have many tags, like sci fi, and classic. And a tag can belong to many books. That's a many to many relationship.

  • Many tags per book
  • Many books per tag
  • Many-to-many

The join table

Neither table can hold a single foreign key. So the database uses a third table, called a join table. Each row links one book, to one tag. JPA creates and fills it for us.

keyvalue
bookid, title
tagid, name
book_tagsbook_id, tags_id
JPAfills the join table

Book with tags

At Many To Many gives each book a set of tags. A set avoids duplicates. The constructor takes any number of tags.

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

    @ManyToMany
    private Set<Tag> tags = new HashSet<>();
    protected Book() {}
    public Book(String title, Tag... tags) {
        this.title = title;
        this.tags.addAll(List.of(tags));
    }
    public String getTitle() { return title; }
    public List<String> tagNames() {
        return tags.stream().map(Tag::getName).sorted().toList();
    }
}

Tagging books

Tag is a simple entity, with a name. The runner saves two tags, and three books. Then it prints each book's tags. Find by tags name searches through the join table. Run it. Dune has both tags. And the classics are Dune, and Emma.

TagDemo.javajava
@Component
public class TagDemo implements CommandLineRunner {
    private final TagRepository tags;
    private final BookRepository books;
    public TagDemo(TagRepository t, BookRepository b) { tags = t; books = b; }

    @Override
    @Transactional
    public void run(String... args) {
        Tag scifi = tags.save(new Tag("sci-fi")), classic = tags.save(new Tag("classic"));
        books.save(new Book("Dune", scifi, classic));
        books.save(new Book("Emma", classic));
        books.save(new Book("Neuromancer", scifi));
        books.findAll().forEach(b -> System.out.println(b.getTitle() + " " + b.tagNames()));
        var found = books.findByTagsName("classic").stream().map(Book::getTitle).toList();
        System.out.println("Classics: " + found);
    }
}
Output
Dune [classic, sci-fi]
Emma [classic]
Neuromancer [sci-fi]
Classics: [Dune, Emma]
Also uses Tag.java
@Entity
public class Tag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    protected Tag() {}
    public Tag(String name) { this.name = name; }
    public String getName() { return name; }
}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToMany
    private Set<Tag> tags = new HashSet<>();
    protected Book() {}
    public Book(String title, Tag... tags) {
        this.title = title;
        this.tags.addAll(List.of(tags));
    }
    public String getTitle() { return title; }
    public List<String> tagNames() {
        return tags.stream().map(Tag::getName).sorted().toList();
    }
}
Also uses TagRepository.java
public interface TagRepository extends JpaRepository<Tag, Long> {}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByTagsName(String name);
}

Summary

At Many To Many links entities through a join table. Spring Data can even query through it, like find by tags name. Next, DTOs for relationships.

Key takeaways
  • @ManyToMany
  • Join table
  • findByTagsName
Next up: DTOs for Relationships — shape the JSON