4

こんにちは、私は Grails 2.1 を使用していますが、良い解決策が見つからない小さな問題があります。いくつかのオブジェクトについてデータベースにクエリを実行していますが、1 つの例外を除いて期待どおりに返され、並べ替えられます。null 値が最初です。

データベースのクエリに使用できるコードは次のとおりです。

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

文字列で並べ替え、すべての null 値を最初ではなく最後に取得する方法はありますか? 私はこのような単純な方法を探しています: Grails/Hibernate: isnull(property) で注文して最後に NULL を取得する方法は?

ありがとう。

4

2 に答える 2

11

あなたはこれを行うことができます:

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 
    }
  }

これにより、null 文字列空の文字列がリストの最後に配置され、残りがアルファベット順に並べ替えられます。

リストの先頭に空の文字列 (および末尾に null) が必要な場合は、Groovy Truth に依存するのではなく、null を明示的にチェックする必要があります。

objects.sort { a, b ->
  a.str == null ? b.str == null ? 0 : 1 : b.str == null ? -1 : a.str <=> b.str
}
于 2012-11-13T15:24:14.690 に答える
0

私はあなたが使うかもしれないと思います:

Object.findAllByObjectTypeAndDateBetween(ObjectType.REGULAR, startDate, stopDate).sort{a, b-> null == a || null == b ? 1 : a <=> b }
于 2012-11-13T15:25:17.367 に答える