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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With