Grails 是内嵌 Hibernate 来进行数据库交互的,级联关系也和 Hibernate 设置一致。常见情形在官方文档里已做了详细介绍,这里讨论的是一对多,而且 “一” 这一方的主键需要指定特定 column 的情形。一对一和 多对多 可以以此类推。有两个表
officer:用户表(由于历史等特殊原因命名此表),主键 user_id
group_user:用户和用户组关系表,主键 group_id + user_id
domain class 如下所示:
class Officer {
String userId
static mapping = {
id name: "userId", generator: "assigned"
version false
}
}
class GroupUser {
String groupId
String userId
static mapping = {
id composite: ["groupId", "userId"]
version false
}
}
class Officer {
String userId
static hasMany = [GroupUsers: GroupUser]
static mapping = {
id name: "userId", generator: "assigned"
version false
GroupUsers lazy: false
}
}
class GroupUser {
String groupId
String userId
Officer officer
static belongsTo = [officer: Officer]
static mapping = {
id composite: ["groupId", "userId"]
version false
officer column: "user_id" // 指定主键列
}
}