2014-05-22 84 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

你說得對,我必須先沖洗實例。謝謝! –