Ms0*_*s01 3 grails groovy hibernate
您好我正在使用Grails 2.1,我有一点问题,我找不到一个好的解决方案.我正在查询数据库中的某些对象,它返回并按预期排序,但有一个例外,空值是第一个.
这是我可以用来查询数据库的代码:
Object.findAllByObjectTypeAndDateBetween(ObjectType.REGULAR, startDate, stopDate).sort {it.str}
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以按字符串排序并获取所有空值而不是第一个?我正在寻找一种简单的方法,不是这样的: Grails/Hibernate:如何通过isnull(属性)来命令最后得到NULL?
谢谢.
tim*_*tes 10
你可以这样做:
objects.sort { a, b ->
!a.str ? !b.str ? 0 : 1 : !b.str ? -1 : a.str <=> b.str
}
Run Code Online (Sandbox Code Playgroud)
扩大解释:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这将在列表的末尾放置空字符串和空字符串,并按字母顺序对其余字符串进行排序
如果你想要列表头部的空字符串(以及尾部的空字符串),你需要显式检查null而不是依赖Groovy Truth:
objects.sort { a, b ->
a.str == null ? b.str == null ? 0 : 1 : b.str == null ? -1 : a.str <=> b.str
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2195 次 |
| 最近记录: |