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,这个例子就可以了,但是如果我想在集合中使用对象,我想我必须重写它
有人知道如何解决这个问题吗
谢谢。我用了你的第三条建议,效果很好!至于你的第一个建议,在我看来,像这样装订是完全可以的。你只需要知道这些指数是不可靠的。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