Grails composite "unique constraint", but how?

I am very close to a solution, but still not so, hope to get help, thanks in advance.

I have a client domain model, for example:

class BoCustomer implements Serializable{ String firstName String lastName String emailID Company company } 

So, I have a primary key = "id", which is fine. Therefore, I need to have a unique restriction that "checks" the following: "only one unique email address for one company" to allow the inclusion of the same email, but only for different companies. Insert ( test@test.com , company identifier: 1 ) and insert ( test@test.com , company identifier: 1 ) is not allowed, but insert ( test@test.com , company identifier: 1 ) and insert ( test @test.com , company id: 2 ).

So I tried:

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

(seems "good", but not quite what I want)

BUT I do not need another column, in my attempt it is called "emailcompany" - but I need something like a unique constraint.

+7
source share
2 answers

You can specify this behavior as one of the main restrictions 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 specification of the unique constraint here http://grails.org/doc/latest/ref/Constraints/unique.html

+7
source

If you want to apply this restriction with a restriction, you can use a special validator to return false if BoCustmer already exists with the same email id and company. Some time has passed since I used it, but I think something like this should work:

 class BoCustomer implements Serializable{ String firstName String lastName String emailID Company company static constraints = { emailID( validator: { val, obj -> def customerWithSameEmailAndCompany = BoCustomer.findByEmailIDAndCompany(obj.emailID, obj.company) return !customerWithSameEmailAndCompany } ) } } 
+1
source