Thursday, March 24, 2011

manually set id of grails domain object

Problem:
if you create a new domain object and set its id in the constructor like this:
Cat catman = new Cat(id:1000, name: "catman", kind: "domestic short haired")
later, if you look at the object the id will be null. what gives?!


Solution:
Its madness, but it works to assign the id after the object is made. Just add
catman.setId(1000);
and you are in business.

Note: if you want to save the object into db after doing this, you must set the id generator to 'assigned'

6 comments:

  1. That's just poor coding on their part.

    ReplyDelete
  2. Yeah poor coding on their part... Like you would have coded it better.

    ReplyDelete
  3. Actually, no id is set after

    Cat catman = new Cat(id:1000, name: "catman", kind: "domestic short haired")

    because you didn't call the save() method.

    ReplyDelete
  4. @unknown:
    you are right of course. I dont remember my exact need for having an id before saving the object, but there was a need to have it be present in the object before the save.

    I was just surprised that cat.setId(1000) would cause the id to be present in the object while doing new Cat(id: 1000) would not.

    ReplyDelete
  5. I know I'm like 3-1/2 years late but...

    This is a feature, not a bug! ID can't be set via the default constructor because the default constructor is often called with the `params` in a controller, and you don't want the end user to be able to change the ID of an object.

    ReplyDelete