Oct
27
2009

Grails GORM and UUIDs

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()
    }
}
Written by Dan in: Grails |

2 Comments »

  • Roshan Shrestha says:

    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?

  • Dan says:

    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!

RSS feed for comments on this post. TrackBack URL


Leave a Reply

Powered by WordPress | Theme: Aeros 2.0 by TheBuckmaker.com