[英]Grails: Duplicates & unique constraint validation
OK here is stripped down version of what I have in my app 好的,这里是我的应用程序的精简版本
Artist domain: 艺术家域:
class Artist {
String name
Date lastMined
def artistService
static transients = ['artistService']
static hasMany = [events: Event]
static constraints = {
name(unique: true)
lastMined(nullable: true)
}
def mine() {
artistService.mine(this)
}
}
Event domain: 事件域:
class Event {
String name
String details
String country
String town
String place
String url
String date
static belongsTo = [Artist]
static hasMany = [artists: Artist]
static constraints = {
name(unique: true)
url(unique: true)
}
}
ArtistService: ArtistService:
class ArtistService {
def results = [
[
name:"name",
details:"details",
country:"country",
town:"town",
place:"place",
url:"url",
date:"date"
]
]
def mine(Artist artist) {
results << results[0] // now we have a duplicate
results.each {
def event = new Event(it)
if (event.validate()) {
if (artist.events.find{ it.name == event.name }) {
log.info "grrr! valid duplicate name: ${event.name}"
}
artist.addToEvents(event)
}
}
artist.lastMined = new Date()
if (artist.events) {
artist.save(flush: true)
}
}
}
In theory event.validate() should return false and event will not be added to artist, but it doesn't.. which results in DB exception on artist.save() 理论上,event.validate()应该返回false,并且不会将事件添加到artist中,但是不会添加..这会导致artist.save()上的数据库异常
Although I noticed that if duplicate event is persisted first everything works as intended. 尽管我注意到如果重复事件一直存在,那么一切都会按预期进行。 Is it bug or feature?
它是错误还是功能? :P
:P
Which version of Grails? 哪个版本的Grails? I've just tested this code in the Grails 1.3.1 console:
我刚刚在Grails 1.3.1控制台中测试了此代码:
new Book(title: "Misery", author: "Stephen King").save()
new Book(title: "The Shining", author: "Stephen King").save()
new Book(title: "Colossus", author: "Niall Ferguson").save(flush: true)
def b = new Book(title: "Colossus", author: "Stephen King")
assert !b.validate()
println b.errors
The assertion passed and the last line generated output like: 断言通过,最后一行生成如下输出:
org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'Book' on field 'title': rejected value [Colossus]; codes [Book.title.unique.error.Book.title,...
Perhaps it was a bug that's now fixed? 也许这是一个已修复的错误?
You should replace artist.addToEvents(event)
by artist.addToEvents(event).save()
and it will work. 您应该将
artist.addToEvents(event)
替换为artist.addToEvents(event).save()
,它将起作用。 Till you didn't call save() method, the validation will not take into account the new created event 直到您没有调用save()方法,验证都不会考虑新创建的事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.