6

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.

Community
  • 1
  • 1
ahanson
  • 2,108
  • 3
  • 23
  • 38
  • 2
    ataylor's answer below is the right way to do it in grails, but I've normally left the database generated IDs alone and added a different string/GUID field on the objects that needed some sort of correlation ID that might get exposed to the end user. That way, you get the normal join/foreign key behavior that grails/hibernate and databases have been tuned for (and writing SQL is easier), but when you need that external ID, you've got that too. – Ted Naleid Nov 24 '10 at 01:14
  • That's what I've done before, but I read that you lose out on default cache that way since it does it by the id. And since I try not to do stuff against the db (or we have an alternate key) I'm gonna give this a shot. – ahanson Nov 24 '10 at 15:55

2 Answers2

9

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"
    }
}
ataylor
  • 64,891
  • 24
  • 161
  • 189
2

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'
    ...
}
Travis Webb
  • 14,688
  • 7
  • 55
  • 109