Can you check combination uniqueness of a field inside a custom validator in a Grails domain class?
Long points
String field1
String field2
Level level
level validator {val,obj->
if(obj.points<1000){
//make sure level is unique with field 1
level unique: ['field1']
}
else{
//make sure level is unique with field 2
level unique: ['field2']
}
}
You can't. The unique constraint is a DDL constraint. It means Grails/Hibernate will create an unique index in your database schema when your app starts, so the constraint remains immutable. The validator constraint is just a closure and it will be executed at runtime every time your domain class is validated.
You have to validate the uniqueness yourself checking the entity in your database using a finder or criteria, rejecting with an error if the unique condition already exists. In your finders, don't forget to exclude the record you are validating.