grailsgrails-ormscaffoldingnatural-key

Gorm change primary key, not found with id null


I have read tons of questions about this and it seems that nobody gets it to work.

I am using grails, and I am creating a class that doesn't have id as the primary key.

I get the message "usuario not found with id null". this is the code of my domain class:

    class Usuario implements Serializable{ 

     String nombre 
     String celular 
     String telefono 
     String apellido 
     String password 
     String nick 

     static mapping = { 
      table 'Usuarios' 
      version false 
      id composite: ['nick'] 
} 
} 

I also tried the normal way with the:

    static mapping = { 
    table 'Usuarios' 
    version false 
     id name: 'nick' 
} 

It actually maps the table the way I want to with the natural key and everything, it inserts the new usuarios, but the gui is incapable of retrieving any objects and shows the error: "usuario not found with id null"

I tried to modify the show(Long id) method, but it wont help either, this is my show method from the controller:

    def show(String nick) {
    def usuarioInstance = Usuario.get(nick)
    if (!usuarioInstance) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'usuario.label', default: 'Usuario'), nick])
        redirect(action: "list")
        return
    }

    [usuarioInstance: usuarioInstance]
}

Solution

  • You need to specify the assigned generator:

    static mapping = {
        ...
        id column: 'nick', generator: 'assigned'
    }
    

    Plus it might be wise to add the following constraints:

    static constraints = {
        nick blank:false, nullable:false, unique: true
    }