繁体   English   中英

grails gorm级联保存最佳实践

[英]grails gorm cascading save best practice

我有一些有效的代码,但是我对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()来使一切正常。

正如@Cregg所提到的,您应该将所有逻辑移到服务上,以便在一个事务中处理对DB的所有调用。 为了不获取瞬时异常,请尝试使用以下命令:

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

您应该创建ErrorController来处理所有异常。 参见示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM