为什么 Grails 中唯一约束字段更新失败

2024-02-11

当我在域类中映射自定义身份属性时,为什么 hibernate 要检查唯一约束?当我更新对象时,尽管发布的字段值与数据库中存储的值相同,但验证失败!即使我没有对表单进行任何更改(确保 dirty: false 并且没有属性绑定错误),也会发生这种情况。 我有一个 Grails 域类,如下所示:

class User {
  Long profileId
  String email
  String username
  String password
  String title
  String firstname
  String lastname
  String zipCode
  Date lastLoginDate

  static constraints = {
      profileId nullable: true, blank: true
      email blank: false, unique: true, email: true
      username blank: false, unique: true
      password blank: false
      lastLoginDate nullable: true

      firstname nullable: true
      lastname nullable: true
      zipCode nullable: true
  }

  static mapping = {
    table 'USER_PROFILE'
    id name:"profileId", column: "profile_id", generator: "sequence", params: [sequence:'userprofile_sequence']
    version false
  }

}

现在,当我创建具有最小属性集的用户时,会创建一条记录。但是当我尝试更新相同的对象时,例如: def user = User.findByUsername('akeel') user.lastLoginDate = new Date() 用户.保存(刷新:true) 什么也没有发生,因为唯一验证检查失败。我可以通过这样做绕过验证 user.save(验证: false, 刷新: true) 但是,这不是一个选项,因为每当用户添加邮政编码时我都需要验证它。

我必须将自定义标识列 profileId 的约束设置为可为空 true,以按照建议解决“映射中的重复列”问题here https://stackoverflow.com/questions/4457727/how-to-solve-grails-error-repeated-column-in-mapping-for-entity-on-existing-pos#comment5139677_4654921.

这个问题和讨论的一模一样here http://grails.1312388.n4.nabble.com/Why-is-uniquely-constrained-field-failing-on-update-td3731538.html,但提出的解决方案对我不起作用。

我正在使用 grails 2.1.2,如果需要其他任何信息来理解该问题,请告诉我。


主键的自定义属性名称似乎在 Grails 中不起作用。我已经用 Grails 2.0.4、2.2.4 和 2.3.4 进行了测试,它们都无法识别profileId作为主键。User.get(1)工作正常,但是user.ident()回报null。我当然会在 Grails JIRA 中提出一个问题。

最简单的解决方案是删除profileId属性并只使用内置的id反而。然后只需删除name:来自自定义映射的值。换句话说,你最终应该得到

id column: "profile_id", generator: "sequence", params: [sequence:'userprofile_sequence']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 Grails 中唯一约束字段更新失败 的相关文章

随机推荐