Skip to content
Advertisement

JPA distinct inner join with Condition on joined table

I have two tables below:

@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;
  }
  ......
  ......
}

I want to get the college object with list of students of a specific department. The SQL query is below:

select *
from COLLEGE c
inner join STUDENT s on c.COLLEGE_ID= s.collegeId
where c.COLLEGE_ID=12345 and s.DEPARTMENT="ENGINEERING";

So far I have tried the below JPA query but it is returning multiple College objects.

SELECT DISTINCT c
FROM COLLEGE c
INNER JOIN c.students s
where c.collegeId= :collegeid and s.department = :department

How to return a single college object with list of students with filtered department?

NOTE: I can’t alter the entity objects used here.

Answer

Try to use this query, using JOIN FETCH instead INNER JOIN:

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