我有一个Grails项目。它的域对象是从现有的WordPress数据库反向工程的。
我有一个名为WpPosts的类,它看起来像这样:
Date postDate
//[...] lots of stuff here which is not important
Long commentCount
static mapping = {
version false
//more blah blah
}
static hasOne = [postAuthor: WpUsers, postParent: WpPosts]
static hasMany = [childPosts: WpPosts]
static constraints = {
postParent nullable: true
//even more blah blah blah
}
因此,一个Post可以将Post作为 child 。但是帖子不一定必须具有“父级”。
在数据库中,如果未定义,则父ID为0。
如果我现在尝试获取我的帖子,grails会尝试获取ID为0的父级。这不存在。所以我得到了
Method threw 'org.hibernate.ObjectNotFoundException' exception.
我当然可以只将父级定义为long值。但是我会放松很多。所以这不是我要采取的解决方案。
预先感谢您的答复!
编辑:现在我的问题是,如果我做错了什么。还是可以定义0为我的空对象?
最佳答案
一种解决方法是拦截getPostParent方法调用并实现您自己的加载逻辑。例如:
class WpPosts {
Date postDate
//[...] lots of stuff here which is not important
Long commentCount
static mapping = {
version false
//more blah blah
}
static hasOne = [postAuthor: WpUsers, postParent: WpPosts]
static hasMany = [childPosts: WpPosts]
static constraints = {
postParent nullable: true
//even more blah blah blah
}
WpPosts getPostParent(Long id) {
if (id == 0) return null
return WpPosts.get(id)
}
}
我没有尝试过,但是它可以帮助您解决问题。
关于wordpress - Grails hasone定义null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22577542/