my own id in GORM

rdmueller picture rdmueller · Oct 27, 2011 · Viewed 10k times · Source

I tried to change the standard 'id' in grails:

calls Book {
  String id
  String title

  static mapping {
    id generator:'assigned'
  }
}

unfortunately, I soon noticed that this breaks my bootstrap. Instead of

new Book (id:'some ISBN', title:'great book').save(flush:true, failOnError:true)

I had to use

def b = new Book(title:'great book')
b.id = 'some ISBN'
b.save(flush:true, failOnError:true)

otherwise I get an 'ids for this class must be manually assigned before calling save()' error.

but that's ok so far.

I then encountered the same problem in the save action of my bookController. But this time, the workaround didn't do the trick.

Any suggestions?

I known, I can rename the id, but then I will have to change all scaffolded views...

Answer

Burt Beckwith picture Burt Beckwith · Oct 27, 2011

That's a feature of databinding. You don't want submitted data to be able to change managed fields like id and version, so the Map constructor that you're using binds all available properties except those two (it also ignores any value for class, metaClass, and a few others).

So there's a bit of a mismatch here since the value isn't managed by Hibernate/GORM but by you. As you saw the workaround is that you need to create the object in two steps instead of just one.