grails - Grails with withTransaction和悲观锁的用法

标签 grails gorm

我正在开发Grails应用程序,并使用控制台插件在运行时执行代码。并且在尝试保存对象时遇到了异常HibernateOptimisticLockingFailureException。

然后在谷歌搜索后知道可以很好地使用withTransaction。

Show.withTransaction {
   Show s=Show.get(1111) // any show id
   s.name=s.name+'1'
   s.save()
}

我还尝试了锁定(悲观锁定),该方法无效,并抛出了乐观锁定异常:
Show s=Show.lock(1111)
s.name=s.name+'1'
s.save(flush:true)

为什么悲观的锁定代码片段无效?

更多细节 :
class Content {

   User createdBy
   User lastUpdatedBy
   Date dateCreated
   Date lastUpdated

   static constraints = {
      createdBy nullable: true
      lastUpdatedBy nullable: true
   }

   static mapping = {
      tablePerHierarchy(false)
   }

}

class Show extends Content {

   String name
   ShowCategory category
   ShowType showType

   static hasMany = [images: Image]

   static constraints = {
      name blank: false, unique: true
      showType nullable: true
      images nullable: true, blank: true
      category nullable: true
   }

   static mapping = {
      table("some_table_show")
      images cascade: 'all-delete-orphan'
      name index: 'name_idx'
      images cache: true
   }

   def afterInsert() {
      Plug.cacheService.deleteCache() // some redis cache usage
   }

   def afterUpdate() {
      Plug.cacheService.deleteCache() // some redis cache usage
   }

}

Exception after using lock (pessimistic locking):
org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [com.myApplication.Show] with identifier [1111]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.myApplication.Show#1111]
    at com.myApplication.cacheService.deleteCache(CacheService.groovy:286)
    at com.myApplication.Show.afterUpdate(Show.groovy:161)
    at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:46)
    at Script1.run(Script1.groovy:17)
    at org.grails.plugins.console.ConsoleService.eval(ConsoleService.groovy:57)
    at org.grails.plugins.console.ConsoleService.eval(ConsoleService.groovy:37)
    at org.grails.plugins.console.ConsoleController$_closure2.doCall(ConsoleController.groovy:61)
    at grails.plugin.cache.web.filter.PageFragmentCachingFilter.doFilter(PageFragmentCachingFilter.java:198)
    at grails.plugin.cache.web.filter.AbstractFilter.doFilter(AbstractFilter.java:63)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.myApplication.Show#1111]
    ... 12 more

最佳答案

通常,withTransaction是一种hack,应避免使用它,主要是因为它允许您在整个代码库中分散事务代码,而不是使用层和分离关注点。请改用事务服务,并根据哪种方法做什么来注释类或单个方法。最终效果是相同的,因为withTransaction和事务服务中使用了相同的基础Spring功能。

如果没有有关代码的外观和所看到的错误消息的更多具体信息,很难提供帮助。如果可以重现,将大有帮助。

如果并发更新的可能性不大,则通常应尝试使用乐观锁定,并在发生偶然冲突时进行处理。当然,在需要的地方使用悲观锁,但对使用它们感到疑惑,因为它们会影响可伸缩性。正如我在对其他答案的评论中提到的那样,所有锁定必须在事务中完成,否则锁定将立即释放。

使用悲观锁定时,很可能会看到Hibernate乐观锁定错误/异常。如果您查看SQL Hibernate生成的更新,通常类似于update <tablename> set foo=?, bar=?, ... where id=? and version=?。 where子句是超定的-仅将id放在其中就足够了,因为它是对应于现有行的id或不是。但是它查看运行该SQL之后的JDBC更新计数,如果为零,则version值必须为off,并且假定这一定是其他人编辑文件并增加版本引起的。

但是奇怪的事情会影响版本。 Hibernate认为集合是一种属性,因此,如果将一个项目添加到集合中会增加所有者的版本。这可能是意外的,例如为作者添加新书将更新作者的版本。不过,Weirder仍然添加了一个新的多对多映射,例如向用户授予角色,同时对角色和用户进行版本控制。这是因为用户的角色集合属性已更改,而且角色的用户集合也已更改。这可能会造成严重破坏,因为您不必锁定用户和角色即可将角色授予用户,也不必锁定集合的元素。

关于grails - Grails with withTransaction和悲观锁的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28149895/

相关文章:

grails - 保存后显示Grails表单可防止历史记录后退按钮显示

mongodb - 更新失败后出现数据无法保存和stackoverflow错误?

Grails 2.3 IntegrationSpec 不能是事务性错误

grails - 找到了IDEA 14和Grails 3.x未索引的远程Maven存储库

grails - Grails可搜索插件找不到导入的MySQL数据

grails - Grails-需要根据联接表上的条件限制提取的行

hibernate - Grails-DuplicateKeyException

mongodb - GORM-获取域类属性的原始DB值

mongodb - GORM for MongoDB:衍生属性(property)?

session - 获取grails计划魔术保存的所有对象的列表