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