grails - Grails:旧版数据库-带有复合ID的记录不会更新

标签 grails gorm updates composite-key legacy-database

我在尝试更新Grails 2.3.7项目上的记录时遇到问题

我不想修改属于复合ID的字段,我只想更新其他字段。

只有一个类,很少有属性,但是每次我尝试更新时,运行此行时都会抛出“非唯一错误”:

personInstance.validate()
if (personInstance.hasErrors()) {
    respond personInstance.errors, view:'create'
    return
}

我的课看起来像这样:
    class Person implements Serializable {

    static constraints = {
        name(unique: lastName)
    }

    static mapping = {
        id generator: 'assigned'
        id composite: ["name", "lastName"]
    }

    //Override equals and hashcode methods
    boolean equals(other) {
    if (!(other instanceof Person)) {
        return false
    }

        other.name == name && other.lastName == lastName
    }
    int hashCode() {
        def builder = new HashCodeBuilder()
        builder.append name
        builder.append lastName
        builder.toHashCode()
    }

    String name
    String lastName
    String description
}

和 Controller Action :
def update() {
   def personInstance = Person.get(new Person(name:params.name, lastName:params.lastName))
   personInstance.properties = params

   personInstance.validate()
   if (personInstance.hasErrors()) {
      respond personInstance.errors, view:'create'
      return
   }

   personInstance.save flush:true

   request.withFormat {/*etc...*/}

}

当我使用validate()时,它会向我抛出Grails唯一键错误,而当我避免验证其为BD而不是唯一PK错误时。
就像Grails在我personInstance.validate()时不知道要插入还是更新。

有没有办法以我没有看到的正确方式来管理它?
还是我被迫避免验证?
难道我做错了什么?

提前致谢。

最佳答案

我相信GORM映射DSL仅需要一个id定义。尝试将您的两个id行合并为这一行:

id generator: 'assigned', composite: ["name", "lastName"]

另外,除了实现Serializable之外,您的域类还应覆盖equalshashCode,如此处“复合主键”中所述:http://grails.org/doc/latest/guide/single.html#identity

关于grails - Grails:旧版数据库-带有复合ID的记录不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26918441/

相关文章:

maven - 如何在 Grails 2.4 中外部化 Maven 凭据

Grails 2.x - 如何保留一个 URL 映射的文件扩展名?

grails - removeFrom删除我所有的多对多关联

go - gorm检查多对多关系是否重复

java - JLabel更新问题

grails - Grails过滤器检测 session 超时

model-view-controller - 通过grails Controller 中的render()发送值

hibernate - Grails 2.5.x GORM持久的人工特性

django - 如何更新我由 DigitalOcean 部署的 Django 网站

c# - 部分更新elastic search NEST 2.x