my own id in GORM

谁都会走 提交于 2019-11-29 17:08:31

问题


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


回答1:


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.




回答2:


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.




回答3:


You need to set the bindable constraint to true for your id prop, e.g.

class Employee {
    Long id
    String name

    static constraints = {
        id bindable: true
    }
}


来源:https://stackoverflow.com/questions/7919634/my-own-id-in-gorm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!