我在尝试更新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
之外,您的域类还应覆盖equals
和hashCode
,如此处“复合主键”中所述:http://grails.org/doc/latest/guide/single.html#identity
关于grails - Grails:旧版数据库-带有复合ID的记录不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26918441/