Oct
27
2009
0

Why I choose to run linux

Automatic Updates automatically restarts your computer for you

Automatic Updates automatically restarts your computer for you

Written by Dan in: General |
Oct
27
2009
2

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 |

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