I have a entity University
having a list of abstract Person
. There are two implementations Student
and Professor
. Now I would like to find all Universities without any Student by a JPA Query.
University-Class
@Entity
public class University {
@OneToMany(targetEntity = Person.class,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
mappedBy = "university",
orphanRemoval = true)
private List<Person> persons = new ArrayList<>();
}
Abstract Person class
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Person {
@OneToOne(fetch = FetchType.LAZY)
private University university;
}
Student Implementation
@Entity
@DiscriminatorValue("STUDENT")
public class Student extends Person {
@NotNull
private String matriculation;
}
A native SQL query would be as following. But I have no idea how to translate that to a JPA Named Query or - also ok - in Criteria API.
select *
from university
where id not in (
select distinct u.id
from university u
join person p on u.id = p.university_id
where p.type = 'STUDENT'
)
;