[英]Grails hasone define null
我有一個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作為孩子。 但是,職位不一定必須具有家長。 如果未定義,則在數據庫中,父ID為0。 如果我現在嘗試獲取我的帖子,grails會嘗試獲取ID為0的父級。這不存在。 所以我得到了
Method threw 'org.hibernate.ObjectNotFoundException' exception.
我當然可以將父級定義為長值。 但是我會放松很多。 所以這不是我要采取的解決方案。
預先感謝您的回答!
編輯:我現在的問題是,如果我做錯了什么。 還是可以定義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)
}
}
我沒有嘗試過,但是它可以幫助您解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.