Grails Domain Error: NULL not allowed for column "USER_GROUP_ID"

Grails Domain Error: NULL not allowed for column "USER_GROUP_ID"

我试图创建一个 SecUser 域对象,其中包含 UserGroup 个对象的集合。每个 UserGroup 应该有一个创建者是 SecUser 类型。 UserGroup 还包含 SecUsers 的集合(例如,创建者在 Facebook 风格应用程序上的好友集合)。到目前为止,我有以下域 类...

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 中,我尝试像这样创建一些 SecUserUserGroup 对象...

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 table 中的 PK 列叫做 USER_GROUP_ID 如果这就是你的全部代码,你就什么也没说,而且你在数据库中有一个约束,它没有'不允许您将其保留为空。因此,您必须更改您的用户组 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
  }
}

希望对您有所帮助。