Search code examples
grailsgrails-orm

To order null values in createcritera.list


I have a problem when sorting a list created using createCriteria. The problem is when I sort according to some a property its value is null , then the whole object is excluded from the list. (the sort parameter is passed through sorttable column )

Here is a sample of my code.

SomeClass.createCriteria().list {
 eq('sth', sth)
if (sort == 'someValue') {
                  nestedClass1 {
                   nestedClass2 {
                    nestedClass3 {
                       order('name', sortOrder)
                              } } }
                        }}

The problem is for instance when nestedCalss1 is null then the whole object is dropped from the list


Solution

  • Association queries like that are inner joins by default, to include nulls you need to use left outer joins, which you can do with createAlias

    import org.hibernate.criterion.CriteriaSpecification
    
    SomeClass.createCriteria().list {
      eq('sth', sth)
      if (sort == 'someValue') {
        createAlias("nestedClass1", "nc1", CriteriaSpecification.LEFT_JOIN)
        createAlias("nc1.nestedClass2", "nc2", CriteriaSpecification.LEFT_JOIN)
        createAlias("nc2.nestedClass3", "nc3", CriteriaSpecification.LEFT_JOIN)
        order("nc3.name", sortOrder)
      }
    }