I have 3 entities which bound with each other.
Group
@Entity
@Table(name = "`group`")
public class Group implements Serializable {
@OneToMany(mappedBy = "group",fetch = FetchType.EAGER)
private List<Student> students;
}
Student
@Entity
@Table(name = "student")
public class Student implements Serializable {
@OneToMany(mappedBy = "student",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private List<Rating> ratings;
}
Rating
@Entity
@Table(name = "rating")
public class Rating implements Serializable {
@Temporal(TemporalType.DATE)
@Column
private Date date;
@ManyToOne
@JoinColumn(name = "id_student")
private Student student;
}
My goal is to find a group with all students on it with their ratings between two dates. All solutions that I tried returns all student ratings not filtered.
@Query(value = "select g from Group g INNER JOIN g.students s ON g.id = :id INNER JOIN s.ratings r ON r.student.id = s.id and r.date between :dateStart and :dateEnd GROUP BY g.id")
@Query(value = "SELECT * FROM Group g INNER JOIN student ON g.id_group = :id RIGHT JOIN rating on student.id_student = rating.id_student and rating.`date` between :dateStart and :dateEnd GROUP BY g.id_group",nativeQuery = true)
@Query(value = "select g from Group g WHERE g.id = :id and g.students IN (select s from g.students s JOIN s.ratings r where r.date between :dateStart and :dateEnd) GROUP BY g.id")
@Query(value = "SELECT g from Group g JOIN g.students s ON g.id = :id JOIN s.ratings r on s.id = r.student.id and r.date between :startMonth and :endMonth")
SELECT * from `group` JOIN student ON `group`.id_group = 1 LEFT JOIN rating on student.id_student = rating.id_student and rating.`date` between '2019-02-01' and '2019-02-28';
Locally this query returns multiple students with a rating between date and one(row) student with the null rating.