Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my own id in GORM

Tags:

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...

like image 215
rdmueller Avatar asked Oct 27 '11 17:10

rdmueller


2 Answers

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.

like image 157
Burt Beckwith Avatar answered Dec 15 '22 00:12

Burt Beckwith


I can't replicate this problem (used Grails 2.0.RC1). I think it might be as simple as a missing equal sign on your static mapping = { (you just have static mapping {)

Here's the code for a domain object:

class Book {
    String id
    String name

    static mapping = {
        id generator:'assigned'               
    }
}

And inside BootStrap.groovy:

def init = { servletContext ->
    new Book(name:"test",id:"123abc").save(failOnError:true)
}

And it works fine for me. I see the id as 123abc.

like image 37
Todd Avatar answered Dec 15 '22 01:12

Todd