Performance: @ManyToMany relationship
This affects database query performance and page load speed when fetching related data in web applications.
Jump into concepts and practice - no test required
@Entity
public class Student {
@ManyToMany(fetch = FetchType.LAZY)
private Set<Course> courses;
}@Entity
public class Student {
@ManyToMany(fetch = FetchType.EAGER)
private Set<Course> courses;
}| Pattern | Database Queries | Data Size | Page Load Impact | Verdict |
|---|---|---|---|---|
| Eager Fetching @ManyToMany | Multiple or large join queries | Large data fetched upfront | Slower LCP due to blocking | [X] Bad |
| Lazy Fetching @ManyToMany | Queries only when accessed | Smaller initial data size | Faster LCP by deferring load | [OK] Good |
@ManyToMany annotation represent in Spring Boot?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());@Entity
class Author {
@ManyToMany
Set<Book> books;
}
@Entity
class Book {
@ManyToMany(mappedBy = "books")
Set<Author> authors;
}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?