Bird
Raised Fist0
Spring Bootframework~20 mins

@ManyToMany relationship in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
ManyToMany Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this @ManyToMany mapping retrieval?
Given two entities Student and Course with a bidirectional @ManyToMany relationship, what will be printed when fetching a student and listing their courses?
Spring Boot
public class Student {
  @ManyToMany
  private Set<Course> courses = new HashSet<>();
  // getters and setters
}

public class Course {
  @ManyToMany(mappedBy = "students")
  private Set<Student> students = new HashSet<>();
  // getters and setters
}

// In service:
Student s = studentRepository.findById(1L).get();
System.out.println(s.getCourses().size());
APrints the number of courses the student is enrolled in, e.g., 3
BThrows a NullPointerException because courses is null
CAlways prints 0 because the collection is not initialized
DThrows a LazyInitializationException if session is closed
Attempts:
2 left
💡 Hint
Think about how JPA initializes collections in a @ManyToMany relationship when accessed inside a transaction.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a bidirectional @ManyToMany relationship?
Select the correct code snippet that defines a bidirectional @ManyToMany relationship between Author and Book entities.
A
@Entity
public class Author {
  @ManyToMany(mappedBy = "authors")
  private Set&lt;Book&gt; books = new HashSet&lt;&gt;();
}
@Entity
public class Book {
  @ManyToMany
  private Set&lt;Author&gt; authors = new HashSet&lt;&gt;();
}
B
@Entity
public class Author {
  @ManyToMany
  private Set&lt;Book&gt; books = new HashSet&lt;&gt;();
}
@Entity
public class Book {
  @ManyToMany(mappedBy = "books")
  private Set&lt;Author&gt; authors = new HashSet&lt;&gt;();
}
C
@Entity
public class Author {
  @OneToMany
  private Set&lt;Book&gt; books = new HashSet&lt;&gt;();
}
@Entity
public class Book {
  @ManyToMany(mappedBy = "books")
  private Set&lt;Author&gt; authors = new HashSet&lt;&gt;();
}
D
@Entity
public class Author {
  @ManyToMany
  private List&lt;Book&gt; books = new ArrayList&lt;&gt;();
}
@Entity
public class Book {
  @ManyToMany(mappedBy = "books")
  private List&lt;Author&gt; authors = new ArrayList&lt;&gt;();
}
Attempts:
2 left
💡 Hint
The owning side does not use mappedBy, the inverse side uses mappedBy with the owning side's field name.
🔧 Debug
advanced
2:30remaining
Why does this @ManyToMany relationship cause a duplicate entry error?
Consider this code snippet where adding the same Course twice to a Student causes a database constraint violation. What is the likely cause?
Spring Boot
Student s = studentRepository.findById(1L).get();
Course c = courseRepository.findById(2L).get();
s.getCourses().add(c);
s.getCourses().add(c);
studentRepository.save(s);
AThe equals and hashCode methods are not overridden in Course entity
BThe Set collection is not properly initialized, allowing duplicates
CThe cascade type is missing, so duplicates are inserted
DThe join table is missing a unique constraint
Attempts:
2 left
💡 Hint
Sets rely on equals and hashCode to avoid duplicates.
lifecycle
advanced
2:30remaining
What happens when you remove an entity from a @ManyToMany collection and save?
Given a Student entity with a @ManyToMany relationship to Course, what happens in the database when you remove a Course from the Student's courses set and save the Student?
Spring Boot
Student s = studentRepository.findById(1L).get();
Course c = courseRepository.findById(2L).get();
s.getCourses().remove(c);
studentRepository.save(s);
AAn exception is thrown because orphanRemoval is not enabled
BThe Course entity is deleted from the database
CNothing changes because cascade remove is not set
DThe link between Student and Course is removed from the join table
Attempts:
2 left
💡 Hint
Removing from a collection updates the join table, not the related entity itself.
🧠 Conceptual
expert
3:00remaining
Which statement about @ManyToMany join tables is true?
Choose the correct statement about the join table used in a @ManyToMany relationship in JPA.
AThe join table cannot be customized in JPA
BThe join table is automatically an entity and can be queried directly
CThe join table must have a composite primary key of both foreign keys by default
DThe join table stores additional entity attributes by default
Attempts:
2 left
💡 Hint
Think about how JPA manages many-to-many relationships internally.

Practice

(1/5)
1. What does the @ManyToMany annotation represent in Spring Boot?
easy
A. A relationship where entities inherit from each other.
B. A relationship where one entity has only one of the other entity.
C. A relationship where entities are unrelated.
D. A relationship where each entity can have many of the other entity.

Solution

  1. Step 1: Understand the meaning of @ManyToMany

    The annotation defines a link where each entity can be related to many instances of the other entity.
  2. Step 2: Compare with other relationship types

    Unlike one-to-one or one-to-many, many-to-many allows multiple connections on both sides.
  3. Final Answer:

    A relationship where each entity can have many of the other entity. -> Option D
  4. Quick Check:

    @ManyToMany = many-to-many link [OK]
Hint: Think: many items linked to many others [OK]
Common Mistakes:
  • Confusing with one-to-one or one-to-many
  • Thinking it means inheritance
  • Ignoring the bidirectional nature
2. Which of the following is the correct way to define a join table in a @ManyToMany relationship?
easy
A. @JoinColumn(name = "student_course")
B. @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id"))
C. @Table(name = "student_course")
D. @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "course_id"), inverseJoinColumns = @JoinColumn(name = "student_id"))

Solution

  1. Step 1: Identify correct @JoinTable usage

    The join table must specify the table name and correctly assign joinColumns and inverseJoinColumns to the owning and inverse sides.
  2. Step 2: Check column names match entities

    joinColumns should refer to the current entity's ID, inverseJoinColumns to the other entity's ID.
  3. Final Answer:

    @JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id")) -> Option B
  4. Quick Check:

    @JoinTable with correct joinColumns = A [OK]
Hint: joinColumns = this entity, inverseJoinColumns = other entity [OK]
Common Mistakes:
  • Swapping joinColumns and inverseJoinColumns
  • Using @JoinColumn instead of @JoinTable
  • Omitting joinColumns or inverseJoinColumns
3. Given the following code snippet, what will be the output when printing student.getCourses().size() after adding two courses to the student?
@Entity
class Student {
  @ManyToMany
  Set<Course> courses = new HashSet<>();

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

@Entity
class Course {}

Student student = new Student();
Course c1 = new Course();
Course c2 = new Course();
student.getCourses().add(c1);
student.getCourses().add(c2);
System.out.println(student.getCourses().size());
medium
A. 2
B. 0
C. 1
D. Compilation error

Solution

  1. Step 1: Understand the collection type and additions

    The courses field is a HashSet, which allows unique elements. Adding two different Course objects increases size to 2.
  2. Step 2: Confirm no errors in adding elements

    Adding elements to the set is valid and no exceptions occur here.
  3. Final Answer:

    2 -> Option A
  4. Quick Check:

    Two courses added = size 2 [OK]
Hint: HashSet size equals unique added elements [OK]
Common Mistakes:
  • Assuming size is 0 because of missing persistence
  • Confusing with list allowing duplicates
  • Expecting compilation error due to missing annotations
4. Identify the error in this @ManyToMany mapping:
@Entity
class Author {
  @ManyToMany
  Set<Book> books;
}

@Entity
class Book {
  @ManyToMany(mappedBy = "books")
  Set<Author> authors;
}
medium
A. The @ManyToMany annotation is missing @JoinTable on both sides.
B. The mappedBy attribute is incorrectly used on the owning side.
C. The collections are not initialized, causing NullPointerException.
D. The entities must extend a common superclass.

Solution

  1. Step 1: Check collection initialization

    The sets 'books' and 'authors' are declared but not initialized, so they are null by default.
  2. Step 2: Understand impact of null collections

    Trying to add or access elements will cause NullPointerException at runtime.
  3. Final Answer:

    The collections are not initialized, causing NullPointerException. -> Option C
  4. Quick Check:

    Uninitialized sets cause null errors [OK]
Hint: Always initialize collections to avoid null errors [OK]
Common Mistakes:
  • Assuming @JoinTable is mandatory on both sides
  • Confusing owning side with inverse side
  • Thinking inheritance is required
5. You have two entities, Student and Club, with a @ManyToMany relationship. You want to add a new club to a student and ensure both sides reflect this change. Which code snippet correctly updates both sides?
hard
A. student.getClubs().add(club); club.getStudents().add(student);
B. student.getClubs().add(club);
C. club.getStudents().add(student);
D. student.setClubs(Set.of(club));

Solution

  1. Step 1: Understand bidirectional @ManyToMany updates

    Both sides must be updated to keep the relationship consistent in memory.
  2. Step 2: Check which code updates both sides

    student.getClubs().add(club); club.getStudents().add(student); adds the club to the student's clubs and the student to the club's students, syncing both sides.
  3. Final Answer:

    student.getClubs().add(club); club.getStudents().add(student); -> Option A
  4. Quick Check:

    Update both sides for consistency [OK]
Hint: Always update both sides of @ManyToMany [OK]
Common Mistakes:
  • Updating only one side causing stale data
  • Replacing collections without adding
  • Ignoring inverse side updates