UPDATED - see answer in comment
I'm aware that CriteriaQuery.orderBy does not support NULLS LAST. I was trying to use a TypedQuery and noticed that it seems to just ignore everything after "NULLS LAST" - doesn't throw any errors, just ignores it:
String sql = "SELECT c FROM Contact c WHERE c.partnerCode =:pCode and c.activeFlag='Y'" +
" ORDER BY c.primaryFlag DESC NULLS LAST, c.lastName ASC";
TypedQuery<Contact> query = em.createQuery(sql, Contact.class);
query.setParameter("pCode", partnerCode);
return query.getResultList();
This returns my result ordered by primary flag descendings, nulls first, ignore sorting on last name.
If I do this:
String sql = "SELECT c FROM Contact c WHERE c.partnerCode =:pCode and c.activeFlag='Y'" +
" ORDER BY c.primaryFlag DESC, c.lastName ASC";
I get both primary and lastname sort, but still end up with nulls first because it's an Oracle DB.
I was mostly surprised that no error message was thrown when I added NULLS LAST and I was hoping that with some syntax tweaks I would be able to get it to accept the NULLS LAST request.
The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table. Auto-boxing is your friend.
The JPA specification defines that during ordering, NULL values shall be handled in the same way as determined by the SQL standard. The standard specifies that all null values shall be returned before or after all non-null values. It's up to the database to pick one of the two options.
The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.
When there are no rows, both query. list() and criteria. list() are returning empty list instead of a null value.
A co-worker provided a workaround for me. Still don't know why the query ignores NULLS LAST but I ended up using this as my workaround:
String sql = "SELECT c FROM Contact c WHERE c.partnerCode =:pCode and c.activeFlag='Y'"
+" ORDER BY nvl(c.primaryFlag, 'N') DESC, c.lastName ASC";
Note: values for the column were 'Y', 'N' or null. Using nvl I am using 'N' in place of null.
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