my own id in GORM

2020-02-27 02:29发布

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

标签: grails gorm
3条回答
ゆ 、 Hurt°
2楼-- · 2020-02-27 02:49

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
    }
}
查看更多
地球回转人心会变
3楼-- · 2020-02-27 02:52

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.

查看更多
够拽才男人
4楼-- · 2020-02-27 03:10

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.

查看更多
登录 后发表回答