Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Criteria API: order by the number of child entities in a one-to-many relationship

I have 2 entities: Faculty and Course which are in a one-to-many relationship, that is - a Faculty can offer multiple courses, but it can also offer none.

I'm trying to sort the faculties by the number of courses they offer, doing this:

criteriaQuery.orderBy(criteriaBuilder.asc(criteriaBuilder.size(root.get(Faculty_.courses))));

The problem is that it fails on

criteriaBuilder.size(root.get(Faculty_.courses)) 

with a NullPointerException because Faculty_.courses is null for certain faculties. Please help me write this in a better way so that it takes into consideration the case when courses is null.

Note: I have to use JPA Criteria API because this is part of a larger query with pagination and stuff. So writing it using query language is not an option.

like image 578
Alex Avatar asked Dec 27 '25 16:12

Alex


1 Answers

You should write Faculty in a way that it always has a list (or set) or courses, which is empty instead of null if there are none:

@OneToMany
private Set<Course> courses = new HashSet<Course>();
like image 66
rolve Avatar answered Dec 31 '25 19:12

rolve