如何更新grails中的重复记录

How to update duplicate records in grails

我们允许数据库中有重复的记录,id 除外。更新记录时,我们希望找到并更新任何重复项。通过研究我发现了Hibernate的事件方法beforeUpdate和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.