我们允许数据库中重复的记录,但id除外。更新记录时,我们要查找并更新所有重复项。通过研究,我发现了Hibernate的事件方法beforeUpdate和afterUpdate。问题是当我发现重复项并开始遍历它们时,出现此错误:
错误:行已被另一个事务更新或删除(或未保存的值映射不正确)
这是我在网域中的afterUpdate代码:
1 def afterUpdate() {
2 println "\n*** afterUpdate ***"
3 def record = this
4
5 DomainObject.createCriteria().list() {
6 ne( 'id', record.id )
7 or {
8 eq( 'storeId', record.storeId )
9 and {
10 eq( 'firstName', record.firstName )
11 eq( 'lastName', record.lastName )
12 eq( 'dateOfBirth', record.dateOfBirth )
13 }
14 }
15 //eq( 'lastUpdated', record.lastUpdated )
16 }.each { dupe ->
17 log.info "syncing ${dupe.id} with ${record.id}"
18 dupe.properties.each{ key, value ->
19 println "*** prop: ${key}: ${value}"
20 }
21 }
22 }
23
错误在第19行。我们正在使用Grails 2.4.4并在Windows上进行开发
最佳答案
看看documentation。请注意本节有关withNewSession
的使用:
class Person {
String name
def beforeDelete() {
ActivityTrace.withNewSession {
new ActivityTrace(eventName: "Person Deleted", data: name).save()
}
}
}
Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like save() and delete() won't result in objects being saved unless you run your operations with a new Session.
Fortunately the withNewSession method lets you share the same transactional JDBC connection even though you're using a different underlying Session.
关于hibernate - 如何更新grails中的重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436657/