Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate order by with nulls last

Hibernate used with PostgreSQL DB while ordering desc by a column puts null values higher than not null ones.

SQL99 standard offers keyword "NULLS LAST" to declare that null values should be put lower than not nulls.

Can "NULLS LAST" behaviour be achieved using Hibernate's Criteria API?

like image 722
mgamer Avatar asked Sep 10 '10 08:09

mgamer


People also ask

What happens to the nulls in the order by?

If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.

Is NULL in HQL query?

You have to use is null and is not null in HQL.

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.

How do you use coalesce in hibernate criteria?

Interface used to build coalesce expressions. A coalesce expression is equivalent to a case expression that returns null if all its arguments evaluate to null, and the value of its first non-null argument otherwise.


1 Answers

This feature has been implemented during Hibernate 4.2.x and 4.3.x releases as previously mentioned.

It can be used as for example:

Criteria criteria = ...; criteria.addOrder( Order.desc( "name" ).nulls(NullPrecedence.FIRST) ); 

Hibernate v4.3 javadocs are less omissive here.

like image 156
José Andias Avatar answered Sep 18 '22 09:09

José Andias