我使用的是grails 2.4.2,但懷疑這與ORM(休眠)通常有關。grails/gorm:指定受'unique'約束的屬性
我想重新分配一個對象集合中的序數屬性。這個重新分配構成了對象的「重新洗牌」。
考慮:
class Bar {
int i
static belongsTo = [foo:Foo]
static constraints = { i unique: 'foo' }
}
class Foo {
static hasMany = [bars:Bar]
static mapping = { bars sort: 'i' }
}
,並
import grails.test.spock.IntegrationSpec
import grails.validation.ValidationException
class FooServiceIntegrationSpec extends IntegrationSpec {
public static final IntRange BAR_RANGE = 0..9
Foo foo
def setup() {
foo = Foo.build()
(BAR_RANGE).each {
Bar bar = Bar.build(i: it, foo: foo)
foo.addToBars(bar)
}
foo.save(flush:true).refresh()
}
void "reshuffling i-s doesn't work"() {
when:
List l = (BAR_RANGE).collect()
use(Collections) {l.shuffle()}
foo.bars.eachWithIndex{b,int index -> b.i=l[index]}
foo.save()
then:
ValidationException ex = thrown()
ex.message =~ 'must be unique'
}
}
如何獲得上述洗牌試圖推過(即不翻倒的唯一約束)?
謝謝:)
刪除一組對象的添加只是這樣我就可以重新添加呢?我對此感覺不太舒服......是這種用例的最佳實踐嗎? – pointyhat 2014-09-03 11:26:44
請在上面找到我的解釋 – saw303 2014-09-03 11:41:17
我認爲這種用例是最壞的做法:) – injecteer 2014-09-03 11:43:04