Using an uuid or guid as id in grails/hibernate

一个人想着一个人 提交于 2019-12-04 10:02:00

You need to set the id as String or UUID (or anything you need).

Below, an example of my class User with another possibility:

import java.util.UUID

class User {

    String id = UUID.randomUUID().toString()

    static mapping = {
        id generator:'assigned'
    }
}

Or you can specify UUID id field in your class without any initializing and set mapping like in this case

class Buyer {

    UUID id
    String name
    String phone
    String email

    static constraints = {
    }

    static mapping = {
        id generator : 'uuid2', type: 'pg-uuid' // pg-uuid because I use postgresql
    }

}

You can take out mapping in Config.groovy

grails.gorm.default.mapping = {
    id generator : 'uuid2', type: 'pg-uuid'
}

and your classes will contain only UUID id field without any redudant code

Here's what I did in my Grails 3 domain class...

class MyClass {    
    static constraints = {
    }

    UUID id
    static mapping = {
        id generator: "UuidGenerator", length: 36, type: "uuid-char"

   }


}

Then here's what I have inside UuidGenerator.groovy

import org.hibernate.id.IdentifierGenerator;
import  org.hibernate.engine.spi.SessionImplementor

import java.security.SecureRandom;

/**
 * 
 */
class UuidGenerator implements IdentifierGenerator {
    Serializable generate(SessionImplementor session, Object object) {

        UUID.randomUUID()
    }
}

For grails 2.x.x my UuidGenerator.groovy looks like this...

import org.grails.datastore.mapping.core.SessionImplementor
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.engine.SessionImplementor;


/**
 * 
 */
class UuidGenerator implements IdentifierGenerator {
    Serializable generate(SessionImplementor session, Object object) {

        return UUID.randomUUID().toString()
    }
}

And my domain class looks like this...

class MyClass {    
    static constraints = {

    }

     String id 
    static mapping = {
        id generator: "com.novadge.UuidGenerator", length:36
    }    
}

If you specify the id as a String and generator type "uuid" you get uuid behavior for your domain in Grails 3 with little effort.

class State  {
    String id
    String state 

    static mapping = {
        id generator: 'uuid'
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!