Search code examples
validationgrailsgrails-ormunique-constraint

Grails unique constraint not working on multiple fields


I've read a lot about uniqueness and constraints in Grails (but maybe not enough)

I can't make the unique constraint to work on multiple fields as explained here:

http://grails.org/doc/1.3.7/ref/Constraints/unique.html

(I'm using grails 1.3.9)

I have 2 domain classes:

class Dog {
    static constraints = {
        humanSsn(unique: ['name', 'breed'])
        //I also tried with just 2 fields, didn't work either.
    }    

    Integer humanSsn
    String name
    String breed
}

class Human {
    static constraints = {
        ssn(unique: true)
    }    
    Integer ssn
    String name
}

It is a legacy DB, so I cant modify the tables.

When I save a Human, I (just to test) save two dogs with the same name, breed and humanSsn

def humanoInstance = new Humano(params)
        if (humanoInstance.save(flush: true)) {
            def newDog = new Dog()
            def newDogTwo = new Dog()
            newDog.name = "n1"
            newDog.breed = "b1"
            newDog.humanSsn = humanInstance.ssn
            println newDog.validate()
            println newDog.getErrors()
            newDog.save(failOnError:true)

            newDogTwo.name = "n1"
            newDogTwo.breed = "b1"
            newDogTwo.humanSsn = humanInstance.ssn
            println newDogTwo.validate()
            println newDogTwo.getErrors()
            newDogTwo.save(failOnError:true)
    }

But it saves anyway the 2 dogs without complaining nor throwing any errors.

true
org.springframework.validation.BeanPropertyBindingResult: 0 error
true
org.springframework.validation.BeanPropertyBindingResult: 0 error

What am I doing wrong?

Thanks in advance.


Solution

  • it may be due to validation works on database level and newDog.save(failOnError:true) doesnot save dog object immediately

    have you try newDog.save(flush:true)

    for first dog and then

    newDogTwo.save(failOnError:true)
    

    it should work