Can somebody show me clear, complete, 100% working way to set string-typed field as ID in grails? I've read the docs, then read all similar ranting on the web, but failed to create a working prototype.
Here is one of my attempts to make you believe I'm not just lazily waiting for somebody to do the job )))
    class User {
  String login
  static hasMany = [apps : Application]
  static constraints = { 
  }
  static mapping = { 
    id generator: 'assigned', name: "login"
  }
}
When you use a natural id you have to use the findBy method instead of the get method as demonstrated in this test:
def user = new User(login: "test")
assertNotNull user.save(flush: true)
user = User.findByLogin("test")
assertNotNull user
assertEquals "test", user.login
Alternately you could use a single field composite id mapping:
class User implements Serializable {
    String login
    static hasMany = [apps: Application]
    static constraints = {
    }
    static mapping = {
        id composite: ['login']
    }
}
Note that composite id domain classes are required to implement Serializable.
The test for the composite id would be:
def user = new User(login: "test")
assertNotNull user.save(flush: true)
user = User.get(new User(login: "test"))
assertNotNull user
assertEquals "test", user.login
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With