2014-05-22 80 views
0

我读过很多关于Grails的独特性和约束(但也许不够)Grails的唯一约束不工作的多个领域

我不能让唯一约束在多个领域的合作如下解释:

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

(我使用Grails 1.3.9)

我有2个领域类:

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 
} 

这是一个遗留数据库,所以我不能修改表。

当我节省了人力,我(只是为了测试)保存两只狗具有相同的名称,品种和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) 
    } 

也可节省反正2只狗没有抱怨,也没有抛出任何错误。

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

我在做什么错?

在此先感谢。

回答

0

这可能是由于验证工作在数据库级别 和newDog.save(failOnError:真)不列入保存狗对象立即

你尝试 newDog.save(flush:true)

的第一狗,然后

newDogTwo.save(failOnError:true) 

它应该工作

+0

你说得对,我必须先冲洗实例。谢谢! –