Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to define custom id generation as default in Grails?

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.

like image 226
ahanson Avatar asked Nov 23 '10 19:11

ahanson


2 Answers

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"
    }
}
like image 168
ataylor Avatar answered Sep 21 '22 02:09

ataylor


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'
    ...
}
like image 38
Travis Webb Avatar answered Sep 22 '22 02:09

Travis Webb