Let’s say that you’ve decided you want to add a globally-unique identifier (GUID/UUID) to one of your domain classes. You might want to do this for portability to other systems or for a variety of reasons. Given that some people in the Grails community don’t recommend using a UUID or string as a primary key, you might find that you want to add a UUID as a separate natural key to your class and set it using GORM’s beforeInsert event hook:
class Person {
String name
String uniqueIdentifier
transient beforeInsert = {
uniqueIdentifier = java.util.UUID.randomUUID().toString()
}
}
This works great, but if you’re like me, in that you like to work with test data while developing, you probably have some code in your BootStrap.groovy file that no longer works. The problem is that GORM’s validate() method does not call event hooks, and that property we just added is not nullable. One small change and we’re back in business:
class Person {
String name
String uniqueIdentifier
stating constraints = {
uniqueIdentifier(nullable:true)
}
transient beforeInsert = {
uniqueIdentifier = java.util.UUID.randomUUID().toString()
}
}
What is the disadvantage of assigning the UUID during construction?
String uniqueIdentifier = java.util.UUID.randomUUID().toString()
For an existing Person read from the DB, there is an extra UUID generated which will be replaced with the value from the database, but this should not be much of an overhead?
I suppose that slight overhead is really the only disadvantage. It might even be worth that small cost in order to tell GORM not to make that field nullable. Good point!