Thursday, March 24, 2011

manually set id of grails domain object

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?!

Its madness, but it works to assign the id after the object is made. Just add
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'


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

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

  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.

  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.

  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.