wordpress - Grails hasone定义null

标签 wordpress hibernate grails groovy

我有一个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/

相关文章:

spring - 当我已经有集成测试时,我应该为 CRUD 操作编写单元测试吗?

java - 退出 java (Grails) 应用程序后, "used"内存未释放

wordpress - CodeIgniter 与 Wordpress,https 与 http,在 AWS 上与 Load Balancer,Wordpress 永久链接不工作

javascript - 如何在离开网站前在 "WordPress menu"上显示一个 javascript 确认框

java - JPA 的 Hibernate 查询提示

java - Autowiring sessionfactory时出错

grails - Grails: token 中的Oauth Twitter用户ID

database - Grails 数据库迁移插件

mysql - 如何使用新的 VPS 在非 root 帐户下安装 apache

html - CSS Bug : Footer under images on Firefox, 但在其他 Web 浏览器上位于图像之上