DEV Community

SOVANNARO
SOVANNARO

Posted on

Spring Boot: JPA Many-to-Many Mapping

Introduction

When designing relational databases in Java, you’ll often encounter situations where multiple entities are related to multiple other entities. This is where Many-to-Many mapping comes into play!

By the end of this article, you’ll learn:

  • What Many-to-Many mapping is.
  • How to implement it using Spring Boot, JPA, and Hibernate.
  • Different ways to set up Many-to-Many relationships.
  • Real-world examples to help you apply it in your projects.

Let’s dive in! 🚀


Image description

What is Many-to-Many Mapping?

A Many-to-Many relationship means that one entity is related to multiple entities, and vice versa.

Real-World Examples:

  • A student can enroll in multiple courses, and a course can have multiple students.
  • An author can write multiple books, and a book can have multiple authors.
  • A product can belong to multiple categories, and a category can have multiple products.

To achieve this, we need a join table that links the two entities together.

Let’s implement this using JPA and Spring Boot! 🔥


Implementing Many-to-Many Mapping in Spring Boot

1️⃣ Many-to-Many Using a Join Table (Recommended ✅)

📌 Step 1: Create the Student Entity

import jakarta.persistence.*;
import java.util.List;

@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 List<Course> courses;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

📌 Step 2: Create the Course Entity

import jakarta.persistence.*;
import java.util.List;

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

    @ManyToMany(mappedBy = "courses")
    private List<Student> students;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

🔹 Explanation:

  • The @ManyToMany annotation defines a many-to-many relationship.
  • The @JoinTable in Student specifies the join table (student_course).
  • The joinColumns and inverseJoinColumns define the foreign keys for both entities.
  • In Course, we use mappedBy = "courses" to indicate that the relationship is managed by Student.

💡 Tip: JPA will automatically create the student_course table with student_id and course_id as foreign keys.


2️⃣ Many-to-Many with an Extra Column in Join Table 📊

If you need to store additional data in the join table (e.g., grade for a student in a course), you should create a separate mapping entity.

📌 Step 1: Create the StudentCourse Entity (Join Table)

import jakarta.persistence.*;

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

    @ManyToOne
    @JoinColumn(name = "student_id")
    private Student student;

    @ManyToOne
    @JoinColumn(name = "course_id")
    private Course course;

    private String grade;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

📌 Modify Student and Course

@OneToMany(mappedBy = "student")
private List<StudentCourse> studentCourses;
Enter fullscreen mode Exit fullscreen mode
@OneToMany(mappedBy = "course")
private List<StudentCourse> studentCourses;
Enter fullscreen mode Exit fullscreen mode

🔹 Why use this approach?

  • You can store extra details like grades, enrollment date, etc..
  • The StudentCourse entity acts as a bridge between Student and Course.

When to Use Many-to-Many Mapping?

Many-to-Many relationships are useful when:
Entities have multiple associations with each other (e.g., students & courses).
You want to avoid duplicate data while maintaining flexibility.
You need to model a complex relationship with extra attributes (e.g., grades in courses).


Conclusion 🎯

In this article, we explored:

  • What Many-to-Many mapping is.
  • How to implement it in Spring Boot using JPA.
  • Different approaches (basic join table vs. additional attributes).
  • When to use it in real-world applications.

Many-to-Many relationships help model complex data structures efficiently. Mastering them will take your backend skills to the next level! 🚀

💬 Got questions? Let me know in the comments! Happy coding! 😃

Image of Datadog

Get the real story behind DevSecOps

Explore data from thousands of apps to uncover how container image size, deployment frequency, and runtime context affect real-world security. Discover seven key insights that can help you build and ship more secure software.

Read the Report

Top comments (1)

Collapse
 
piotr_b5f3fb16a99232443b1 profile image
Piotr

A better approach is using a table between many-to-many relation

Image of Datadog

Keep your GPUs in check

This cheatsheet shows how to use Datadog’s NVIDIA DCGM and Triton integrations to track GPU health, resource usage, and model performance—helping you optimize AI workloads and avoid hardware bottlenecks.

Get the Cheatsheet

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay