我有以下两个表:
@Entity
@Table(name="COLLEGE")
public class College {
private Long collegeId;
private List<Student> students;
@Id
@Column(name = "COLLEGE_ID")
public Long getCollegeId() {
return this.collegeId;
}
public void setCollegeId(final Long collegeId) {
this.collegeId= collegeId;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "college")
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<Student> getStudents() {
if (this.students== null) {
this.students= new ArrayList<>();
}
return this.students;
}
public void setStudents(List<Student> students){
this.students = students
}
}
@Entity
@Table(name="STUDENT")
public class Student {
private Long studentId;
private College college;
private String name;
private String department;
@Id
public Long getStudentId() {
return this.studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COLLEGE_ID")
public getCollege() {
return this.college;
}
public setCollege(College college) {
this.college = college;
}
......
......
}
我想获取带有特定
college
的students
列表的department
对象。 SQL查询如下:select *
from COLLEGE c
inner join STUDENT s on c.COLLEGE_ID= s.collegeId
where c.COLLEGE_ID=12345 and s.DEPARTMENT="ENGINEERING";
到目前为止,我已经尝试了下面的JPA查询,但是它返回了多个
College
对象。SELECT DISTINCT c
FROM COLLEGE c
INNER JOIN c.students s
where c.collegeId= :collegeid and s.department = :department
如何使用过滤后的
college
返回带有students
列表的单个department
对象?注意:我无法更改此处使用的实体对象。
最佳答案
尝试使用此查询,使用JOIN FETCH代替INNER JOIN:
SELECT DISTINCT c FROM College c
JOIN FETCH c.students s
WHERE c.collegeId= :collegeid
AND s.department = :department