2013-10-29 52 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