JPA独特的内部联接,在联接表上具有Condition

时间:2018-09-19 15:21:26

标签: java sql oracle jpa jpql

我在下面有两个表格:

@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的{​​{1}}列表。 SQL查询如下:

department

到目前为止,我已经尝试了以下JPA查询,但它返回了多个select * from COLLEGE c inner join STUDENT s on c.COLLEGE_ID= s.collegeId where c.COLLEGE_ID=12345 and s.DEPARTMENT="ENGINEERING"; 对象。

College

如何返回带有过滤后的SELECT DISTINCT c FROM COLLEGE c INNER JOIN c.students s where c.collegeId= :collegeid and s.department = :department 的{​​{1}}列表的单个college对象?

注意:我无法更改此处使用的实体对象。

1 个答案:

答案 0 :(得分:1)

尝试使用此查询,使用JOIN FETCH代替INNER JOIN:

SELECT DISTINCT c FROM COLLEGE c 
       JOIN FETCH c.students s
            WHERE c.collegeId= :collegeid 
                  AND s.department = :department