Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define null-handling in Spring Data JPA sorts?

I need my data to be ordered by null and not null only. Like below:

Column A
null 
null 
null
8 
10
5

Meaning once all the null values are on top, the rest of the values should not be sorted at all and come as is. Any idea how this can be done using jpa query/ native query.

like image 635
Priyabrat Nanda Avatar asked Apr 01 '15 21:04

Priyabrat Nanda


People also ask

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.

Does Spring JPA return null or empty list?

The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return Null . The problem is that a parameter is given to the method and is not used anywhere in the Query.

Is null in Spring JPA?

IS NULL Query. The first method is very simple to create because null parameters in the query methods are interpreted as IS NULL by default. To demonstrate this, let's create a test. Now let's pass “D” as the value of the name parameter and null as the value of the email parameter to our query method.


2 Answers

If you project use Spring Boot, you can add YML configuration like this, it work for me.

spring:
  jpa:
    properties:
        hibernate.order_by.default_null_ordering: last
like image 119
hang gao Avatar answered Nov 15 '22 16:11

hang gao


Use JPQL and you will be happy.

SELET f FROM Foo f ORDER BY f.name NULLS LAST
like image 34
Henrique Fernandes Cipriano Avatar answered Nov 15 '22 16:11

Henrique Fernandes Cipriano