Thursday 15 May 2008

Be unique ... and enforce constraints

Some of our unique constraints for domain objects are a bit loose at the moment. Where we have unique constraints based on multiple properties they are only enforced by the database when the hibernate session is flushed. However, it is possible to get grails to enforce multi property constraints so that a call to validate() will fail, rather than letting it fall through and cause a data access/jdbc exception.

For example, today we added a unique constraint on to Asset, where the originalAssetId had to be unique per Site.

To do this we added the constraint:

static constraints = {
.......
.......
originalAssetId(unique:'site')
.......
.......
}
The 'unique' property can also accept a list of properties. The following snippet would make originalAssetId unique by site and state.

static constraints = {
.......
.......
originalAssetId(unique:['site','state'])
.......
.......
}
Check out the grails docs for a full description.

No comments: