我认为您想要的可以描述为多对多关系users
,并在 Connection集合上应用了某种约束。至于单向/双向,我相信您可以根据您的用例来完成任何一项任务——尽管单向可能更难映射/配置。
我还没有测试过这个,但是双向多对多应该是这样的
class Connection {
...
Set users = [] //ensure users exists, constraints won't work on null
static belongsTo = [User]
static hasMany = [users: User]
static constraints = {
users maxSize: 2
}
}
class User {
...
static hasMany = [connections: Connection]
}
我没有想到一个单向的例子,但我相信你可能需要使用一个额外的映射类。
同样,我没有对此进行测试,但这里有一个带有映射类的单向多对多示例
class Connection {
...
Set users = []
static hasMany = [users: ConnectionUser]
static constraints = {
users maxSize: 2
}
}
class User {
...
}
class ConnectionUser {
User user
Connection connection
//or for cascading effects
//static belongsTo = [connection: Connection]
...
... //lots of additional code to manage adding,
... //removing, updating Connection-to-User relationships
}
Connection 知道用户,但用户不知道他们所属的 Connection。如果您使用映射类路由,则需要手动管理连接到用户的关系。看一下Spring Security Core PersonAuthority类的映射类示例。