2

By default, when you create a domain object in grails, it adds the "id" column and sets it to auto-increment in the DB.

I want to supply the id parameter when I create/save an object, not use any kind of generate (its for a small number of static pieces of data which I want the ID to be fixed to the values I give).

There are other benefits I want, e.g. to be able to create an object in memory with the correct ID, without having to read it from the DB then make this object a "contains" type relationship with another object, if that makes sense.

Grails has documenation for the id column, but doesnt say how to disable auto-increment and allow an ID to be passed into the domain object constructor:

http://grails.org/doc/2.1.0/ref/Database%20Mapping/id.html

1 Answer 1

5

Look at the mappings for the column. According to the documentation you can use assigned like this:

static mapping = { id generator: 'assigned' } 

According to the hibernate documentation assigned behaves as such:

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

Sign up to request clarification or add additional context in comments.

4 Comments

Sadly, this does not seem to work. If I try it, and pass in a id to the constructor, and save it, I get: IdentifierGenerationException: ids for this class must be manually assigned before calling save()
@JohnLittle so why dont you assign it manually before calling save?
I was hoping to pass in the id in the constructor, e.g. new Status(id:1, name: "active").save(). I see that I could do this: s=new Status(name:"active"); s.id = 1, s.save(), which is more painful as I have a lot of static items to set in the bootstrap. I looked at overriding the Status constructor, and passing in _id and assigning it, and all the other fields manually, but this is also significant overhead.
By default the id property is not "bindable", i.e. it's ignored with using the map constructor, and when setting properties in bulk (e.g. foo.properties = params). Either set it explicitly after the constructor call, or make the id property bindable with the bindable constraint. Note that making the property bindable this is somewhat unsafe; id and version are auto-excluded by Grails (in addition to the default class and metaClass exclusions that Groovy adds) because only Hibernate should set or update those values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.