Disable the natively generated identity value feat

2019-09-03 06:45发布

问题:

The following is my Domain class details.

class Age {
    String agetype
    static constraints = {
    }

}

I am using HeidiSQL. I want to drop the id column that is generated automatically.And set primary key as 'agetype'. what I can I do?

回答1:

Identifier can be customized easily inside the mapping block, if the default id is not required.

class Age {
    String agetype

    static mapping = {
        id name: 'agetype', 
           column: 'AGE_TYPE', // if the column name is AGE_TYPE
           generator: 'assigned' // Unique String should assigned for agetype
    }

    static constraints = {
        agetype bindable: true //identifiers are not bindable by default
    }
}

With the above setup, you should be able to create Age as:

new Age(agetype: 'Teen').save(flush: true)

Above will through a primary key violation if run again.

Refer docs for more details about customizing id and column as required.