【问题标题】:Grails MongoDB Update object with Association具有关联的 Grails MongoDB 更新对象
【发布时间】:2015-07-22 22:37:19
【问题描述】:

当我尝试更新与 Profile 对象具有 hasOne 关联的用户域模型时,我似乎无法理解当前哪里出错了。

我的领域模型如下:

class User {

    static hasOne = [profile: Profile]
    static fetchMode = [profile: 'eager']

    ObjectId id
    String username
}

class Profile {
   static belongsTo = [user: User]
   ObjectId id
   String familyName
   String givenName
}

我最初可以使用个人资料来持久化用户,但在尝试更新用户对象时出现验证错误。

Validation error occurred during call to save():
- Field error in object 'co.suitable.User' on field 'profile.familyName': rejected value [null]
- Field error in object 'co.suitable.User' on field 'profile.givenName': rejected value [null]

我可以在保存对象之前打印出 user.profile ID 和 user.profile.familyName。像下面这样:

println(user.profile.familyName)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)

但在保存之前我仍然会收到验证错误,我想println(user.profile.familyName) 调用正在获取配置文件对象,如果它尚未加载,我认为设置 fetchMode 会处理。

当我这样做时,对象能够成功持久化并保存:

user.profile = Profile.findById(user.profile.id)
println(user.profile.id.toString())
user.save(flush: true, failOnError: true)

我可以将它包装在一个服务中,但我希望如果可能的话,我希望有一个由 Grails 处理的解决方案。非常感谢任何建议或想法。

【问题讨论】:

    标签: mongodb grails


    【解决方案1】:

    您不应该将 SQL DB 的逻辑应用于 Mongo 1 对 1。Mongo 和其他面向文档的 DB 最初并不打算存储集合之间的连接。有一些变通方法,例如db-refs,但应谨慎使用。

    对于您的情况 - 使用 hasOne - 我建议使用 mongo 的 subdocuments(镜像为 GORM 的 embedded 对象)而不是引用:

    class User {
    
        ObjectId id
        String username
    
        Profile profile
        static embedded = [ 'profile' ]
    
    }
    
    class Profile {
       String familyName
       String givenName
    }
    

    因此,您按照原始用途使用 mongo。查询也更简单、更快捷。

    【讨论】:

    • 我同意我应该远离传统的 SQL 结构,所以你的回答确实提供了一个很好的解决方案,但我也希望能够了解为什么 Grails 能够自动获取用户中的属性到 Profile 关联,但当时间到了,它们似乎消失了?这可以在我的 Save() 调用之前的 println() 中看到。
    猜你喜欢
    • 2019-05-28
    • 2019-10-12
    • 2019-10-16
    • 1970-01-01
    • 2014-10-29
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多