我试图创建一个SecUser
域对象,其中包含UserGroup
对象的集合。每个UserGroup
应具有一个创建者,该创建者是SecUser
的一种。 UserGroup
还包含SecUsers
的集合(例如,Facebook风格应用程序上创建者的 friend 集合)。到目前为止,我有以下域类...
class SecUser implements Serializable {
static constraints = {
....
usergroups nullable: true
}
static mapping = {
...
usergroups cascade: 'all-delete-orphan'
}
static hasMany = [
...
usergroups: UserGroup
]
}
class UserGroup {
SecUser creator;
static belongsTo = SecUser;
static hasMany = [
members : SecUser
]
static constraints = {
creator nullable: false
members nullable: true, maxSize: 100
}
}
在
Bootstrap.groovy
中,我尝试像这样创建一些SecUser
和UserGroup
对象...def secuser = new SecUser(username: "username", password: "password");
def group1 = new UserGroup(title: "Friends", description: "friends");
def group3 = new UserGroup(title: "Colleagues", description: "colleagues");
secuser.addToUsergroups(group1);
secuser.addToUsergroups(group2);
但是我遇到一个错误,它说...
ERROR spi.SqlExceptionHelper - NULL not allowed for column "USER_GROUP_ID"; SQL statement:
insert into sec_user_usergroups (sec_user_id, creator_id) values (?, ?) [23502-176]
Error |
2015-07-28 11:04:49,208 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Hibernate operation: could not execute statement; SQL [n/a]; NULL not allowed for column "USER_GROUP_ID"; SQL statement:
insert into sec_user_usergroups (sec_user_id, creator_id) values (?, ?) [23502-176]; nested exception is org.h2.jdbc.JdbcSQLException: NULL not allowed for column "USER_GROUP_ID"; SQL statement:
insert into sec_user_usergroups (sec_user_id, creator_id) values (?, ?) [23502-176]
Message: Hibernate operation: could not execute statement; SQL [n/a]; NULL not allowed for column "USER_GROUP_ID"; SQL statement:
insert into sec_user_usergroups (sec_user_id, creator_id) values (?, ?) [23502-176]; nested exception is org.h2.jdbc.JdbcSQLException: NULL not allowed for column "USER_GROUP_ID"; SQL statement:
insert into sec_user_usergroups (sec_user_id, creator_id) values (?, ?) [23502-176]
我猜该程序告诉我它无法完成
addToUsergroups
操作,因为UserGroup
尚未获得id
(因为尚未保存)。但是,有没有一种方法可以在没有addToUsergroups
的情况下完成id
操作? (因为没有UserGroup
不应创建SecUser
)。还是我的域对象的设计有问题?提前致谢!
最佳答案
我猜您在UserGroup表中的PK列称为USER_GROUP_ID,如果这就是您的所有代码,则您什么都没说,并且数据库中存在一个约束,不允许您将其保留为空。因此,您必须更改UserGroup ID,以指定PK列的调用方式不同。
class UserGroup {
SecUser creator;
static belongsTo = SecUser;
static hasMany = [
members : SecUser
]
static mapping = {
id column: 'user_group_id'
}
static constraints = {
creator nullable: false
members nullable: true, maxSize: 100
}
}
希望能帮助到你。