Grails one-to-many 排序

来源:互联网 发布:无网络远程监控 编辑:程序博客网 时间:2024/05/29 16:19

在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)    }}
0 0
原创粉丝点击