2012-11-13 30 views
3

你好,我正在使用Grails 2.1,我有一個小問題,我找不到一個好的解決方案。我正在查詢數據庫中的某些對象,並按預期方式返回並對其進行排序,只有一個例外,空值是第一個。在排序關閉中,如何最後得到空值?

這裏是我可以用它來查詢數據庫的代碼:

Object.findAllByObjectTypeAndDateBetween(ObjectType.REGULAR, startDate, stopDate).sort {it.str} 

有什麼辦法,我可以通過字符串進行排序,並讓所有的空值,而不是最後的第一?我正在尋找一個簡單的方法,不是這樣的: Grails/Hibernate: how to order by isnull(property) to get NULLs last?

謝謝。

+0

如果從數據庫要排序檢查此[文章](http://stackoverflow.com/a/34685962/2561990) – ladriangb

+0

如果你想從數據庫中排序數據檢查這[帖子](http://stackoverflow.com/a/34685962/2561990) – ladriangb

回答

8

你可以這樣做:

objects.sort { a, b -> 
    !a.str ? !b.str ? 0 : 1 : !b.str ? -1 : a.str <=> b.str 
} 

擴大瞭解釋:

objects.sort { a, b -> 
    if(!a.str) {    // If a.str is null or empty 
    if(!b.str) {   // If b.str is null or empty 
     return 0    // They are the same 
    } 
    else {     // a.str is empty or null, but b.str has value 
     return 1    // b.str should come before a.str 
    } 
    else {      // a.str has value 
    if(!b.str) {   // b.str is null or empty 
     return -1    // b.str should come after a.str 
    } 
    else {     // Both have value, 
     return a.str <=> b.str // Compare them 
    } 
    } 

這將使空字符串空字符串在列表的末尾,剩下的按字母順序排序

如果您想要列表頭部的空字符串(以及尾部的空值),您需要明確檢查空而不是依賴Groovy的真相:

objects.sort { a, b -> 
    a.str == null ? b.str == null ? 0 : 1 : b.str == null ? -1 : a.str <=> b.str 
} 
+0

感謝你這樣,你一樣有用:) – Ms01

+1

@cubsink找到我相信一個更短的方式 –

+0

不幸的是我有一個異常說它不能比較值。 '無法使用第一個解決方案將值爲'Avalue'的project.Str與值爲'Anothervalue'的project.Str進行比較。我想要背後的所有東西。但是,只會有1個空值並且沒有空字符串。 – Ms01

0

我想你可以使用:

Object.findAllByObjectTypeAndDateBetween(ObjectType.REGULAR, startDate, stopDate).sort{a, b-> null == a || null == b ? 1 : a <=> b } 
+0

對不起,你的解決方案甚至不會迭代正確的值,我害怕。我想你錯過了.str – Ms01