自动绑定时多对多关系中对象的HashCode方法

时间:2013-10-03 11:35:57

标签: hibernate grails

我有两个具有多对多关系的对象。文章可以在不同的部分,一个部分可以有很多文章。

class Article {
    String title
    static belongsTo = Section
    Set<Section> sectionSet = [] as Set

    static hasMany = [
           sectionSet: Section
    ]
}

class Section {
    String title
    String uniqueUrl   // an unique identifier for the section

    List<Article> articleList = []
    static hasMany = [
            articleList: Article
    ]

    static mapping = {
        uniqueUrl(unique: true)
    }

    boolean equals(o) {
        if (this.is(o)) return true
        if (getClass() != o.class) return false

        Section section = (Section) o

        if (uniqueUrl != section.uniqueUrl) return false

        return true
    }

    int hashCode() {
        return uniqueUrl.hashCode()
    }

}

现在我想通过绑定来自控制器的参数来创建一篇新文章,如下所示:

params = [title: "testArticle", "sectionSet[0].id": "1"] // a section with ID=1 exists in database
Article article = new Article(params) // NullPointerException here because I add this article into the section and uniqueUrl for calculating hashCode() is null

我遇到了hashCode的问题,因为没有从db加载ID为1的部分,因此它的字段都是null。如果我不覆盖equals和hashCode,该示例工作正常,但我想如果我想在集合中使用对象,我必须重写...

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  1. 如果要使用List sectionSet [0] .id的索引绑定,请不要使用任何Set。只列表!!!
  2. 使用命令对象。
  3. 添加文章应遵循:

    def selectedSections = Section.findAll(params.list(&#39; section.id&#39;));

    def article = new Article(params)

    selectedSections.each {it.addToArticleList(article).save(true)}