0
0
Spring Bootframework~5 mins

@ManyToMany relationship in Spring Boot

Choose your learning style9 modes available
Introduction

The @ManyToMany relationship connects two sets of data where each item in one set can relate to many items in the other set, and vice versa. It helps model real-world connections like students enrolled in many courses.

When you have two groups that can have multiple links to each other, like authors and books.
When modeling social networks where users can follow many users and be followed by many.
When managing tags that can apply to many posts, and posts can have many tags.
When you want to keep track of memberships where people can join many clubs and clubs have many members.
Syntax
Spring Boot
@ManyToMany
@JoinTable(
  name = "table_name",
  joinColumns = @JoinColumn(name = "this_entity_id"),
  inverseJoinColumns = @JoinColumn(name = "other_entity_id")
)
private Set<OtherEntity> relatedEntities;
Use @ManyToMany on both sides of the relationship to link the two entities.
The @JoinTable annotation defines the join table that holds the connections between the two entities.
Examples
This example shows a Student entity linked to many Course entities using a join table named 'student_course'.
Spring Boot
@Entity
public class Student {
  @Id
  private Long id;

  @ManyToMany
  @JoinTable(
    name = "student_course",
    joinColumns = @JoinColumn(name = "student_id"),
    inverseJoinColumns = @JoinColumn(name = "course_id")
  )
  private Set<Course> courses = new HashSet<>();
}
The Course entity links back to Student using mappedBy to indicate the owning side is in Student.
Spring Boot
@Entity
public class Course {
  @Id
  private Long id;

  @ManyToMany(mappedBy = "courses")
  private Set<Student> students = new HashSet<>();
}
Sample Program

This program defines Student and Course entities linked with a @ManyToMany relationship. Alice is enrolled in Math and Science courses. The output lists Alice's courses.

Spring Boot
import jakarta.persistence.*;
import java.util.*;

@Entity
public class Student {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @ManyToMany
  @JoinTable(
    name = "student_course",
    joinColumns = @JoinColumn(name = "student_id"),
    inverseJoinColumns = @JoinColumn(name = "course_id")
  )
  private Set<Course> courses = new HashSet<>();

  public Student() {}
  public Student(String name) { this.name = name; }

  public void addCourse(Course course) {
    courses.add(course);
    course.getStudents().add(this);
  }

  public Set<Course> getCourses() { return courses; }
  public String getName() { return name; }
}

@Entity
public class Course {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String title;

  @ManyToMany(mappedBy = "courses")
  private Set<Student> students = new HashSet<>();

  public Course() {}
  public Course(String title) { this.title = title; }

  public Set<Student> getStudents() { return students; }
  public String getTitle() { return title; }
}

// Usage example (in a service or main method):
Student alice = new Student("Alice");
Course math = new Course("Math");
Course science = new Course("Science");

alice.addCourse(math);
alice.addCourse(science);

System.out.println(alice.getName() + " is enrolled in:");
for (Course c : alice.getCourses()) {
  System.out.println("- " + c.getTitle());
}
OutputSuccess
Important Notes

Always maintain both sides of the relationship to keep data consistent.

The join table stores the connections and usually has two foreign keys.

Use Set instead of List to avoid duplicate links.

Summary

@ManyToMany links two entities where each can have many of the other.

Use @JoinTable to define the join table that connects them.

Keep both sides updated to avoid data mismatches.