Bird
Raised Fist0
Spring Bootframework~5 mins

@ManyToMany relationship in Spring Boot - Cheat Sheet & Quick Revision

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
Recall & Review
beginner
What does the @ManyToMany annotation represent in Spring Boot?
It represents a relationship where multiple records in one entity relate to multiple records in another entity, like students enrolled in many courses and courses having many students.
Click to reveal answer
intermediate
How do you define the owning side of a @ManyToMany relationship?
The owning side is the entity that controls the relationship and usually has the @JoinTable annotation to define the join table and join columns.
Click to reveal answer
intermediate
What is the purpose of the @JoinTable annotation in a @ManyToMany relationship?
It defines the join table that holds foreign keys linking the two entities, specifying the table name and the join columns for both sides.
Click to reveal answer
advanced
Why is it important to manage both sides of a @ManyToMany relationship in code?
Because changes to the relationship must be reflected on both entities to keep data consistent and avoid unexpected behavior.
Click to reveal answer
advanced
What happens if you omit the mappedBy attribute in a bidirectional @ManyToMany relationship?
JPA treats both sides as owning sides, creating two separate join tables, which can cause data duplication and confusion.
Click to reveal answer
In a @ManyToMany relationship, which annotation specifies the join table?
A@JoinTable
B@JoinColumn
C@Entity
D@Table
What does the mappedBy attribute do in a @ManyToMany relationship?
AIndicates the inverse side that maps to the owning side
BDefines the join table name
CSpecifies the owning side of the relationship
DMarks the entity as a database table
Which side should have the @JoinTable annotation in a bidirectional @ManyToMany?
ABoth sides
BOnly the owning side
COnly the inverse side
DNeither side
What kind of database table does a @ManyToMany relationship create?
AA single table with foreign keys
BNo additional table
CTwo separate tables with no link
DA join table linking the two entity tables
If you forget to update both sides of a bidirectional @ManyToMany in code, what might happen?
AThe database will automatically fix it
BNo effect at all
CData inconsistency or unexpected behavior
DThe application will crash immediately
Explain how to set up a bidirectional @ManyToMany relationship between two entities in Spring Boot.
Think about how two friends share a group chat and both need to know about it.
You got /4 concepts.
    Describe the role of the join table in a @ManyToMany relationship and how it connects the entities.
    Imagine a guest list that shows which guests attend which parties.
    You got /4 concepts.

      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