Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String IDs in grails - how exactly can it be done?

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"
  }

}

like image 886
shabunc Avatar asked Dec 21 '22 07:12

shabunc


1 Answers

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
like image 84
James Allman Avatar answered Dec 29 '22 12:12

James Allman