What's the best way to define custom id genera

2019-04-29 07:35发布

I want to switch my domain classes to use a variable length UUID for their ids. I don't want to simply display sequential ids on the URL for people to try and mess with. I've written a custom version of the Java UUID method to allow for variable length so I can have shorter ids for models that won't grow large.

I found this thread that explained how to modify the default mapping so I can change to 'assigned'. Modify Id generation for a Grails Plugin

What's the best way to also configure a default beforeInsert (to generate the custom UUID) and tell Grails I want to use strings for ids instead of integers?

I tried adding grails.gorm.default.beforeInsert to the config but that didn't work.

标签: grails gorm
2条回答
神经病院院长
2楼-- · 2019-04-29 07:47

To make grails use strings for the ids, just declare a property String id. To populate it with a custom UUID, I'd use a hibernate id generator instead of beforeInsert. Create a class that extends org.hibernate.id.IdentifierGenerator, then add an id generator mapping like this to your domain class:

class MyIdGenerator extends IdentifierGenerator {
    Serializable generate(SessionImplementor session, Object object) {
        return MyUUID.generate()
    }
}

class MyDomain {
    String id
    static mapping = {
        id generator:"my.package.MyIdGenerator", column:"id", unique:"true"
    }
}
查看更多
【Aperson】
3楼-- · 2019-04-29 07:59

This question is old but it's still showing up in searches. This currently the best way to do this, circa Grails 2.3. (I'm using postgres, so notice the "pg-uuid" type. Adapt this to your particular data store).

UUID uuid    
static mapping = {
    uuid generator: 'uuid2', type: 'pg-uuid'
    ...
}
查看更多
登录 后发表回答