@ManyToMany and when to use a join entity instead
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A student takes many courses, and a course has many students. The database needs a third table to store those pairs, and JPA offers two ways to map it.
@ManyToMany with @JoinTable
A link table is a third table that stores a many-to-many relationship, with one foreign key to each side, such as student_courses (student_id, course_id). JPA maps it with @ManyToMany and @JoinTable, or as an entity of its own.
A student takes many courses and a course has many students. The link table below stores each pair once.
-- students (student_id, full_name) and courses (course_id, title) are plain tablesCREATE TABLE student_courses ( -- the link table student_id INT NOT NULL, course_id INT NOT NULL, joined_on DATE NOT NULL DEFAULT (CURRENT_DATE), PRIMARY KEY (student_id, course_id), FOREIGN KEY (student_id) REFERENCES students (student_id), FOREIGN KEY (course_id) REFERENCES courses (course_id));Example 1 · Student.java and Course.java: @ManyToMany with a Set
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.school;
import java.util.Collections;import java.util.LinkedHashSet;import java.util.Set;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.JoinTable;import jakarta.persistence.ManyToMany;import jakarta.persistence.OrderBy;import jakarta.persistence.Table;
@Entity@Table(name = "students")public class Student {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "student_id") private Integer id;
@Column(name = "full_name") private String fullName;
@ManyToMany @JoinTable(name = "student_courses", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) @OrderBy("id") private Set<Course> courses = new LinkedHashSet<>();
protected Student() { }
public Student(String fullName) { this.fullName = fullName; }
public void join(Course course) { courses.add(course); course.students().add(this); }
public void leave(Course course) { courses.remove(course); course.students().remove(this); }
public Set<Course> getCourses() { return Collections.unmodifiableSet(courses); }
public Integer getId() { return id; } public String getFullName() { return fullName; }}
package com.shoplite.lab.school;
import java.util.HashSet;import java.util.Set;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.ManyToMany;import jakarta.persistence.Table;
@Entity@Table(name = "courses")public class Course {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "course_id") private Integer id;
private String title;
@ManyToMany(mappedBy = "courses") // inverse side private Set<Student> students = new HashSet<>();
protected Course() { }
public Course(String title) { this.title = title; }
Set<Student> students() { // for Student's helpers only return students; }
public Integer getId() { return id; } public String getTitle() { return title; }}
// SchoolService.printCourses(1)@Transactional(readOnly = true)public void printCourses(int studentId) { Student student = students.findById(studentId).orElseThrow(); List<String> titles = student.getCourses().stream().map(Course::getTitle).toList(); System.out.println(student.getFullName() + ": " + titles);}DEBUG SQL - select s1_0.student_id,s1_0.full_name from students s1_0 where s1_0.student_id=? DEBUG SQL - select c1_0.student_id,c1_1.course_id,c1_1.title from student_courses c1_0 join courses c1_1 on c1_1.course_id=c1_0.course_id where c1_0.student_id=? order by c1_0.course_id Asha Rao: [Java Basics, DSA, Spring Boot]
What this code does
- Loading the courses joins the link table to
courses:from student_courses c1_0 join courses c1_1 ... where c1_0.student_id=?. joinColumnsisstudent_id(this side),inverseJoinColumnsiscourse_id(the other side);@OrderBy("id")sorts by course id.- A
LinkedHashSetkeeps insertion order for new students;joinandleaveare the helpers that change both sets.
@ManyToMany maps a collection where both sides can have many partners, and @JoinTable names the link table and its two columns: joinColumns points at this entity, inverseJoinColumns at the other one. These teaching tables are not part of ShopLite; they exist only in the lab database.
One side owns the link and the other uses mappedBy, exactly as in a one-to-many. Here Student.courses owns it, so a student joining a course writes one row into student_courses, and the helper methods join and leave keep both sets in step. You never write an entity for student_courses: Hibernate inserts and deletes its rows as the collection changes, which holds only while the link table has nothing but the two ids.
Why link tables grow extra columns
The school now wants the date each student joined a course. Where does joined_on go when the link table has a third column?
Example 2 · SchoolService.join(): a link row with only two ids
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/school/SchoolService.java (one method)@Transactionalpublic void join(int studentId, int courseId) { Student student = students.findById(studentId).orElseThrow(); Course course = courses.findById(courseId).orElseThrow(); student.join(course); System.out.println(student.getFullName() + " joined " + course.getTitle());}
// called as join(2, 3): Ravi Kumar joins Spring BootDEBUG SQL - select s1_0.student_id,s1_0.full_name from students s1_0 where s1_0.student_id=? DEBUG SQL - select c1_0.course_id,c1_0.title from courses c1_0 where c1_0.course_id=? DEBUG SQL - select c1_0.student_id,c1_1.course_id,c1_1.title from student_courses c1_0 join courses c1_1 on c1_1.course_id=c1_0.course_id where c1_0.student_id=? order by c1_0.course_id DEBUG SQL - select s1_0.course_id,s1_1.student_id,s1_1.full_name from student_courses s1_0 join students s1_1 on s1_1.student_id=s1_0.student_id where s1_0.course_id=? Ravi Kumar joined Spring Boot DEBUG SQL - insert into student_courses (student_id,course_id) values (?,?)
What this code does
- The INSERT has only
student_idandcourse_id.joined_onis not mapped, so MySQL fills it from its default (CURRENT_DATE); with no default, the insert would fail. - The two link SELECTs load both sets because the
joinhelper adds tostudent.coursesandcourse.students. - There is no way to pass a date: the
Set<Course>has nowhere to keep it. That is the limit of@ManyToMany.
Real link tables rarely stay at two columns. The moment the business wants to know something about the link itself, the table gets a new column: when the student joined (joined_on), the grade, the fee paid. ShopLite's order_items is a link table between orders and products, born with two extra columns: quantity and unit_price, the price on the day of the order.
@ManyToMany cannot read or write those columns. Its collection holds only the other entity (Set<Course>), so there is nowhere to put joined_on or quantity, and Hibernate inserts link rows with only the two ids, so other columns get their database default or the insert fails. That is why @ManyToMany is rare in real applications: it is right only for a pure, attribute-free link, such as tags on a product.
A join entity: OrderItem with two @ManyToOne links
A join entity is an ordinary entity for a link table, with one @ManyToOne to each side plus its own fields. ShopLite's OrderItem is one: order, product, quantity and unitPrice.
The many-to-many between orders and products becomes two many-to-one links you already know.
Example 3 · OrderItem.java as a join entity, and the unique pair
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.order;
import java.math.BigDecimal;
import com.shoplite.lab.product.Product;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.GeneratedValue;import jakarta.persistence.GenerationType;import jakarta.persistence.Id;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.Table;
@Entity@Table(name = "order_items")public class OrderItem {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_item_id") private Integer id;
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_id") private Order order; // the owning side: holds order_id
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id") private Product product;
private int quantity;
@Column(name = "unit_price") private BigDecimal unitPrice;
protected OrderItem() { }
public OrderItem(Product product, int quantity, BigDecimal unitPrice) { this.product = product; this.quantity = quantity; this.unitPrice = unitPrice; }
void setOrder(Order order) { // package-private: only Order calls it this.order = order; }
public BigDecimal lineTotal() { return unitPrice.multiply(BigDecimal.valueOf(quantity)); }
public Integer getId() { return id; } public Order getOrder() { return order; } public Product getProduct() { return product; } public int getQuantity() { return quantity; } public BigDecimal getUnitPrice() { return unitPrice; }}
package com.shoplite.lab.order;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.product.Product;import com.shoplite.lab.product.ProductRepository;
@Servicepublic class OrderLineService {
private final OrderRepository orders; private final OrderItemRepository orderItems; private final ProductRepository products;
OrderLineService(OrderRepository orders, OrderItemRepository orderItems, ProductRepository products) { this.orders = orders; this.orderItems = orderItems; this.products = products; }
@Transactional(readOnly = true) public void printLines(int orderId) { Order order = orders.findById(orderId).orElseThrow(); for (OrderItem item : order.getItems()) { System.out.println(item.getProduct().getName() + " x " + item.getQuantity() + " @ " + item.getUnitPrice() + " = " + item.lineTotal()); } System.out.println("Total: " + order.total()); }
/** Adds a second line for a product the order already has. */ @Transactional public void addLine(int orderId, int productId, int quantity) { Order order = orders.findById(orderId).orElseThrow(); Product product = products.findById(productId).orElseThrow(); OrderItem item = new OrderItem(product, quantity, product.getPrice()); order.addItem(item); orderItems.save(item); }}--- printLines(14) DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? DEBUG SQL - select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? order by i1_0.order_item_id DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? Redmi Note 13 5G x 1 @ 17999.00 = 17999.00 DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? boAt Airdopes 141 x 1 @ 1299.00 = 1299.00 Total: 19298.00 --- addLine(14, 1, 1): a second line for the Redmi DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? DEBUG SQL - select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG SQL - insert into order_items (order_id,product_id,quantity,unit_price) values (?,?,?,?) WARN error - HHH000247: ErrorCode: 1062, SQLState: 23000 WARN error - Duplicate entry '14-1' for key 'order_items.uq_order_items_order_product' DataIntegrityViolationException: Duplicate entry '14-1' for key 'order_items.uq_order_items_order_product'
What this code does
- Each
OrderItemrow links one order and one product and carries its own data:quantity,unitPriceand the computedlineTotal(). - Order 14 already has product 1, so the second line breaks
uq_order_items_order_product. MySQL reports the pair as'14-1'and the whole transaction rolls back. - The service should check first and add to the quantity instead; the constraint is the safety net that also stops two requests racing each other.
Order.items and, if you ever need it, Product.orderItems are the two one-to-many sides. A join entity also gives the link a natural home for behaviour, such as lineTotal(), and for rules, such as quantity 1 to 10; with @ManyToMany there would be no class for them.
Start with a join entity whenever the link has, or will soon have, data of its own. Moving from @ManyToMany to a join entity later means rewriting every place that used the collection.
Predict the output
Which mapping fits?
Read the link table and pick the better mapping.
Round 1 of 3
Tags on a product.
Unique (order_id, product_id): surrogate id or @EmbeddedId
A surrogate id is a meaningless generated key, such as order_item_id, used as a row's primary key instead of a combination of real columns. order_items adds UNIQUE (order_id, product_id) so a product still appears once per order.
An order may hold each product only once, with a quantity. Which key enforces that rule?
Example 4 · StudentCourse.java: a composite key with @EmbeddedId and @MapsId
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
package com.shoplite.lab.school;
import java.io.Serializable;
import jakarta.persistence.Column;import jakarta.persistence.Embeddable;
/** The composite primary key of student_courses: both columns together. */@Embeddablepublic record StudentCourseId( @Column(name = "student_id") Integer studentId, @Column(name = "course_id") Integer courseId) implements Serializable {}
package com.shoplite.lab.school;
import java.time.LocalDate;
import jakarta.persistence.Column;import jakarta.persistence.EmbeddedId;import jakarta.persistence.Entity;import jakarta.persistence.FetchType;import jakarta.persistence.JoinColumn;import jakarta.persistence.ManyToOne;import jakarta.persistence.MapsId;import jakarta.persistence.Table;
/** One row of student_courses as an entity, so the extra column joined_on can be mapped. */@Entity@Table(name = "student_courses")public class StudentCourse {
@EmbeddedId private StudentCourseId id;
@MapsId("studentId") // fills id.studentId from this link @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "student_id") private Student student;
@MapsId("courseId") // fills id.courseId from this link @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "course_id") private Course course;
@Column(name = "joined_on") private LocalDate joinedOn;
protected StudentCourse() { }
public StudentCourse(Student student, Course course, LocalDate joinedOn) { this.id = new StudentCourseId(student.getId(), course.getId()); this.student = student; this.course = course; this.joinedOn = joinedOn; }
public Student getStudent() { return student; } public Course getCourse() { return course; } public LocalDate getJoinedOn() { return joinedOn; }}
interface StudentCourseRepository extends JpaRepository<StudentCourse, StudentCourseId> {
List<StudentCourse> findByStudentIdOrderByJoinedOn(Integer studentId);}
// SchoolService.printLinks(1)@Transactional(readOnly = true)public void printLinks(int studentId) { for (StudentCourse link : links.findByStudentIdOrderByJoinedOn(studentId)) { System.out.println(link.getCourse().getTitle() + " since " + link.getJoinedOn()); }}DEBUG SQL - select sc1_0.student_id,sc1_0.course_id,sc1_0.joined_on from student_courses sc1_0 where sc1_0.student_id=? order by sc1_0.joined_on DEBUG SQL - select c1_0.course_id,c1_0.title from courses c1_0 where c1_0.course_id=? Java Basics since 2026-06-01 DEBUG SQL - select c1_0.course_id,c1_0.title from courses c1_0 where c1_0.course_id=? DSA since 2026-07-01 DEBUG SQL - select c1_0.course_id,c1_0.title from courses c1_0 where c1_0.course_id=? Spring Boot since 2026-08-01
What this code does
StudentCourseIdis a record marked@Embeddable(Hibernate 7 supports records as embeddables);implements Serializableis required for id classes.@MapsId("studentId")says thestudentlink fillsid.studentId, so the same column is both a foreign key and part of the primary key.- Now
joined_onis a normal field. EachgetCourse()is a lazy load, one SELECT per course: fine for three rows, a fetch join for long lists (Performance Traps module).
Saving a second line for the same product fails in MySQL, which protects the data even if the service forgets the check. The other design is a composite primary key: the two foreign keys together are the key, as in student_courses. JPA maps it with an @Embeddable id class holding both values, @EmbeddedId in the entity, and @MapsId on each @ManyToOne so the links fill the id parts.
The surrogate id is simpler in practice: one Integer id for URLs and repositories, no id class, and save() can tell new from old by a null id. Use @EmbeddedId when the schema already has a composite key, as student_courses does.
Set vs List for @ManyToMany
A bag is what Hibernate calls an unordered List collection. It cannot tell which link row matches which element, so after one change it may delete all the link rows and insert the remaining ones again. A Set avoids this.
Remove one course from a student. How many statements does Hibernate send with a Set, and with a List?
Example 5 · leave(): a Set deletes one row, a List deletes them all
Runs in: the relations-lab practice project (Spring Boot 4.1, ShopLite database)
// SchoolService.leave(1, 2): Asha Rao leaves DSA@Transactionalpublic void leave(int studentId, int courseId) { Student student = students.findById(studentId).orElseThrow(); Course course = courses.findById(courseId).orElseThrow(); student.leave(course); System.out.println(student.getFullName() + " left " + course.getTitle());}
// Run 1: private Set<Course> courses = new LinkedHashSet<>();// Run 2: private List<Course> courses = new ArrayList<>(); (everything else the same)--- Run 1: Set Asha Rao left DSA DEBUG SQL - delete from student_courses where student_id=? and course_id=? SELECT * FROM student_courses WHERE student_id = 1; +------------+-----------+------------+ | student_id | course_id | joined_on | +------------+-----------+------------+ | 1 | 1 | 2026-06-01 | | 1 | 3 | 2026-08-01 | +------------+-----------+------------+ --- Run 2: List (fresh database) Asha Rao left DSA DEBUG SQL - delete from student_courses where student_id=? DEBUG SQL - insert into student_courses (student_id,course_id) values (?,?) DEBUG SQL - insert into student_courses (student_id,course_id) values (?,?) SELECT * FROM student_courses WHERE student_id = 1; +------------+-----------+------------+ | student_id | course_id | joined_on | +------------+-----------+------------+ | 1 | 1 | 2026-10-16 | | 1 | 3 | 2026-10-16 | +------------+-----------+------------+
What this code does
- With a
Set, Hibernate deletes exactly the row(1, 2); the other rows keep theirjoined_ondates from June and August. - With a
List, Hibernate deletes all of Asha's link rows and inserts the two that remain: 3 statements instead of 1. - The reinserted rows got today's date from the column default: the real joining dates are lost. On a big list this is also slow.
Use a Set for every @ManyToMany. With a List (a bag), removing one course makes Hibernate delete every link row of that student and insert the rest again. That costs N+1 statements instead of one, and it destroys data: any extra column in the link table, such as joined_on, is reset to its default for the reinserted rows. With a Set, Hibernate deletes exactly one row.
A Set needs equals and hashCode; inside one transaction the default identity versions work, because Hibernate gives one object per row. The Entities and Mapping module covers id-based versions for entities compared across transactions.
Next step
Check your understanding
12 quick questions