2013-10-29 80 views
0

我有一些工作代碼,但我對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()中添加了一切工作。

+0

只是一個參考,將所有save()調用移動到服務中,或者至少在withTransaction {}中移動。但一個服務將是最好的。 – Gregg

回答

1

由於@Cregg提到你應該將所有的邏輯移動到服務中,以便處理在一次事務中對數據庫的所有調用。拿不到瞬態異常嘗試使用以下:

profile.save(flush: true, failOnError:true) 

應該創建ErrorController來處理所有的異常。見example

+0

flush:true working。我能夠刪除前2個節點(),並以profile.save結尾(flush:true),節省了級聯。太好了!作爲一個附註,我確實在服務中使用了這塊代碼。 – spock99