Grails domain class: unique constraint for multiple columns
Asked Answered
E

1

53

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?

Encipher answered 28/9, 2011 at 12:44 Comment(1)
I was browsing the web and in particular stackoverflow without finding an answer. In the end, I found the solution in the Grails reference although all other Grails documentation examples only contaning the single column case. Didn't know that self-answering is not allowed within 8 hoursEncipher
D
90
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']
Denunciate answered 28/9, 2011 at 13:3 Comment(2)
In grails 3 it is written "userName unique: 'countryId'" docs.grails.org/latest/ref/Constraints/unique.htmlPettit
@CarlosParraga that's just a variant of the same thing. That same syntax can be used with versions of Grails prior to 3.x as well.Denunciate

© 2022 - 2024 — McMap. All rights reserved.