在grails domain中,如下方法可用于one-to-many时对many一方数据进行排序:
- 在one的一方的domain中设置SortedSet属性,值为many一方的集合,使用static
hasMany指明many一方的domain类。 - 在many一方的domain中,实现Comparable接口,实现compareTo方法。
- 在one的一方同时可以在mapping中设置many一方的lazy为true/false。
代码如下:
one的一方的domain:
class Twitter {
String content
Date dateCreated
Date lastUpdated
SortedSet comments
static constraints = {
content(nullable: false,blank: false)
}
static hasMany = [comments:TwitterComment]
static mapping = {
version(false)
comments(lazy:false)
}
}
many的一方的domain(此处为双向关联):
class TwitterComment implements Comparable<TwitterComment>{
Twitter twitter
String content
Date dateCreated
Date lastUpdated
static constraints = {
twitter(nullable: false)
content(nullable: false)
}
static belongsTo = [
twitter:Twitter
]
@Override
int compareTo(TwitterComment o) {
return o.dateCreated.compareTo(dateCreated)
}
}