Grails domain class: unique constraint for multiple columns

GrailsOrmUnique ConstraintGrails Domain-ClassGrails Validation

Grails Problem Overview


Suppose a simple Grails domain class:

class Account {
    String countryId;

    String userName;

    String password;

    static constraints = {
        ...???...
    }
}

It is required that user names are unique for a particular countryId, thus there must be a unique contraint on two columns. How to express this in the constraints definition?

Grails Solutions


Solution 1 - Grails

userName(unique: ['countryId'])

You can include as many other properties in the array that make up the other properties that must be considered in the "unique" constraint on the username.

So, for example if you wanted to make userName unique within a countryId and provinceId it would look like this:

userName(unique: ['countryId', 'provinceId']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrainer198View Question on Stackoverflow
Solution 1 - GrailsJoshua MooreView Answer on Stackoverflow