我有一些工作代码,但我对GORM和级联保存有点模糊。这里是我的对象模型:grails gorm级联保存最佳实践
class Profile {
PhotoAlbum photoAlbum
static constraints = {
photoAlbum(nullable:true)
}
}
class PhotoAlbum {
static hasMany = [photos:Photo]
static belongsTo = [profile:Profile]
}
class Photo {
static belongsTo = PhotoAlbum
}
这里是我工作的代码保存一个新的照片对象:
Photo photo = new Photo()
if (!profile.photoAlbum) { profile.photoAlbum = new PhotoAlbum(profile:profile) }
profile.photoAlbum.addToPhotos(photo)
if (!photo.save()) {
def json = [
status:'fail',
message:messageSource.getMessage('label.photo.validate.failed.message', [photo.errorStrings].toArray(), LocaleContextHolder.locale)
]
return json
}
if (!profile.photoAlbum.save()) {
def json = [
status:'fail',
message:messageSource.getMessage('label.photo.validate.failed.message', [profile.photoAlbum.errorStrings].toArray(), LocaleContextHolder.locale)
]
return json
}
if (!profile.save()) {
def json = [
status:'fail',
message:messageSource.getMessage('label.photo.validate.failed.message', [profile.errorStrings].toArray(), LocaleContextHolder.locale)
]
return json
}
else {
def json = [
status:'success',
message:messageSource.getMessage('label.photo.insert.success.message', null, LocaleContextHolder.locale)
]
return json
}
这似乎是一个大量的代码和错误检查保存新照片对象。当我在网站和书籍中查看grails示例时,我没有看到很多错误检查。在我的情况下,如果照片无法保存,服务必须返回一个json错误字符串到客户端。我已阅读GORM Gotchas 2的帖子,但我仍然不清楚级联保存。
我确实发现,如果我不调用photo.save()和profile.photoAlbum.save(),只是调用profile.save(),我会得到瞬态异常。所以我在photo.save()和profile.photoAlbum.save()中添加了一切工作。
只是一个参考,将所有save()调用移动到服务中,或者至少在withTransaction {}中移动。但一个服务将是最好的。 – Gregg