grails composite "unique constraint", but how?

grailsInvas0r picture grailsInvas0r · Nov 6, 2011 · Viewed 7.8k times · Source

I'm very close to a solution but anything is still wrong, hope to get help, thanks in advance.

I have a Customer domain model like:

class BoCustomer implements Serializable{

    String firstName
    String lastName
    String emailID
    Company company
}

So, I have a primary key = "id" that's okay. So further I need kind of unique constraint that "checks" the following: "only one unique email address for one company" so that inserting the same e-mail should be allowed but only for different companies. Inserting ([email protected], company-id: 1) and inserting ([email protected], company-id: 1) is not allowed, but inserting ([email protected], company-id: 1) and inserting ([email protected], company-id: 2) is allowed.

So I tried so far:

static mapping = {
    id column: "customer_id", generator: "identity"
    emailcompany composite: ['emailID', 'company'], unique: true
}

(seems to be "good", but not exactly what I want)

BUT i don't want another column, in my try called "emailcompany" - but I need something like a unique constraint.

Answer

fredGalvao picture fredGalvao · Nov 8, 2011

You can specify this behaviour by one of the main constraints available: unique

class BoCustomer implements Serializable{

    String firstName
    String lastName
    String emailID
    Company company

    static constraints = {
        emailID(unique: 'company')
            // OR
        company(unique: 'emailID')
    }
}

You can see the full spec of the unique constraint here http://grails.org/doc/latest/ref/Constraints/unique.html