【问题标题】:HashCode method for objects in many-to-many relationship when autobinding自动绑定时多对多关系中对象的HashCode方法
【发布时间】:2013-10-03 11:35:56
【问题描述】:

我有两个具有多对多关系的对象。一篇文章可以在不同的版块中,一个版块可以有很多篇文章。

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 的问题,因为 ID 为 1 的部分不是从 db 加载的,因此它的字段都是空的。如果我不覆盖 equals 和 hashCode,该示例可以正常工作,但我想如果我想使用集合中的对象,我必须覆盖......

有人知道怎么解决吗?

【问题讨论】:

    标签: hibernate grails


    【解决方案1】:
    1. 如果你想绑定 List sectionSet[0].id 的索引,不要使用任何 Set !!!仅列出!!!
    2. 使用命令对象。
    3. 添加文章应如下:

      def selectedSections = Section.findAll(params.list('section.id'));

      def article = new Article(params)

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-28
    • 2019-07-20
    • 2012-08-12
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    相关资源
    最近更新 更多