Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL Hibernate NULLS LAST being ignored

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.

like image 884
headlikearock Avatar asked Apr 30 '13 16:04

headlikearock


People also ask

How hibernate handle null values?

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.

How does JPA Handle null values?

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.

What is the difference between JPQL and Hql?

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.

Does Hibernate query List return null?

When there are no rows, both query. list() and criteria. list() are returning empty list instead of a null value.


1 Answers

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.

like image 147
headlikearock Avatar answered Sep 22 '22 19:09

headlikearock