【问题标题】:Self-Referencing Relationship with Properties in Grails?与 Grails 中的属性的自引用关系?
【发布时间】:2013-09-09 12:42:11
【问题描述】:

我有以下自引用关系。一个用户可以有很多朋友。

class User {

  String name

  hasMany = [friends: User]
}

Hibernate 在我的 MySql 数据库中所做的是创建一个表 user_user。

现在我想将 Date lastUpdated 之类的属性添加到好友关系中。我该怎么做?

【问题讨论】:

    标签: mysql spring hibernate grails grails-2.0


    【解决方案1】:

    我在这里可能不正确,但似乎不可能。原因是user_user 表没有直接的域支持它,因为它只代表域之间的关系而不是域本身。

    一种选择是在映射器类中管理关系,就像Spring Security Core PersonAuthority class 的方式一样

    class Friendship implements Serializable {
    
       User user //may need some mappedBy config in User class
       User friend
       Date lastUpdated
    
       ... //helper methods, see PersonAuthority class for example
    
       static mapping = {
          id composite: ['user', 'friend']
          version false
       }
    }
    

    由于它是一个实际的域类,您可以包含其他属性,例如您的 lastUpdated

    对 cme​​ts 的更新: 你真的应该查看PersonAuthority class 的例子——你不需要在你的 User 类中明确声明任何关系,因为它们现在由 Friendship 管理。您可以在 User 类中添加辅助方法来查询 Friendship 中的关系。

    例如:

    class User ...
    
      ...
      Set<User> getFriends() {
        Friendship.findAllByUser(this).collect { it.friend } as Set
      }
    }
    

    【讨论】:

    • 在用户类中我要做什么?
    • 如何在 User 类中进行映射?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多