I'm wondering about what is the best ways to fetch entity relations.
Assume we have these these entities:
public class Student {
@Id
@GeneratedValue
private Long id;
@NotBlank
@Size(min = 5, max = 64)
@Column(unique=true)
private String nickname;
@NotBlank
@Email
@Column(unique=true)
private String email;
@NotBlank
@Size(min = 8, max = 64)
private String password;
@ManyToMany(mappedBy = "students", fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Set<StudyGroup> studyGroups;
}
And
public class StudyGroup {
@Id
@GeneratedValue
private Long id;
@NotBlank
private String name;
@ManyToOne
private Student creator;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
private Set<Notification> notifications;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Set<Student> students;
}
I know of three different ways to fetch the relations.
Fetch the study groups from the student by fetching the student and the using student.getStudyGroups();
Using projection. Something like:
ReturnStudyGroups findStudentById(Long id); interface ReturnStudyGroups { Set<StudyGroup> getStudyGroups(); }
In the study group repository, making a custom query that searches for study groups that have the student in the students field.
What is the best way for fetching the relations? Is projection faster then the first method mentioned?