我有以下的自引用关系。一个用户可以有许多朋友。
class User {
String name
hasMany = [friends: User]
}Hibernate在我的MySql数据库中所做的是创建一个表user_user。
现在,我想向朋友关系中添加一个类似Date lastUpdated的属性。我该怎么做呢?
发布于 2013-09-09 23:55:57
我在这里可能是不正确的,但这似乎是不可能的。原因是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这样的其他属性。
更新到评论:你真的应该看看PersonAuthority class中的一个例子-你不需要在你的User类中显式声明任何关系,因为它们现在是由Friendship管理的。您可以在User类中添加helper方法来查询关系的Friendship。
例如:
class User ...
...
Set<User> getFriends() {
Friendship.findAllByUser(this).collect { it.friend } as Set
}
}https://stackoverflow.com/questions/18698475
复制相似问题