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.
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"
}
}
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'
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With