我有一些工作代碼,但我對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