Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate 自动绑定时多对多关系中对象的HashCode方法_Hibernate_Grails - Fatal编程技术网

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

Hibernate 自动绑定时多对多关系中对象的HashCode方法,hibernate,grails,Hibernate,Grails,我有两个具有多对多关系的对象。一篇文章可以分为不同的部分,一个部分可以有许多文章 class Article { String title static belongsTo = Section Set<Section> sectionSet = [] as Set static hasMany = [ sectionSet: Section ] } class Section { String title

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

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()
    }

}
我遇到了hashCode的问题,因为ID为1的节不是从db加载的,因此它的字段都是空的。如果我不重写equals和hashCode,这个例子就可以了,但是如果我想在集合中使用对象,我想我必须重写它

有人知道如何解决这个问题吗

  • 如果要与List sectionSet[0]的索引绑定,请不要使用任何集合。id!!!唯一列表
  • 使用命令对象
  • 新增条款如下:

    def selectedSections=Section.findAll(参数列表('Section.id')

    def article=新项目(参数)

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


  • 谢谢。我用了你的第三条建议,效果很好!至于你的第一个建议,在我看来,像这样装订是完全可以的。你只需要知道这些指数是不可靠的。Grails的文档中也有:
    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