Grails hasone define null

I have a Grails project. It’s Domain Objects are reverse engineered from an existing WordPress database.

I have a Class Called WpPosts it looks like this:

Read More
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
    }

So it is possible for a Post to have Posts as children. But a post must not necessarily have a Parent.
Within the Database the parent id is 0 if it is not defined.
If I try to get My post now grails trys to get a Parent with the id 0. This does not exist. So I get an

Method threw 'org.hibernate.ObjectNotFoundException' exception.

I could of course just define parent as long value. But I would loose a lot of comfort. So this is not a solution I want to take.

Thanks for your answers in advance!

EDIT: My question is now if I did do anything wrong. Or can I define that 0 is my null object?

Related posts

Leave a Reply

1 comment

  1. One way of handling this could be to intercept the getPostParent method call and implement your own loading logic. For example:

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

    I haven’t tried this, but it may help you overcome your issue.