Grails使用withTransaction和悲观锁定

Grails使用withTransaction和悲观锁定,grails,gorm,Grails,Gorm,我正在开发一个Grails应用程序,并使用控制台插件在运行时执行代码。在尝试保存对象时,出现异常HibernateOptimisticLockingFailureException 然后在谷歌知道如何使用运行良好的withTransaction之后 Show.withTransaction { Show s=Show.get(1111) // any show id s.name=s.name+'1' s.save() } 我还尝试过lock(悲观锁定),但它不起作用,并引发

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

然后在谷歌知道如何使用运行良好的withTransaction之后

Show.withTransaction {
   Show s=Show.get(1111) // any show id
   s.name=s.name+'1'
   s.save()
}
我还尝试过lock(悲观锁定),但它不起作用,并引发乐观锁定异常:

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

悲观锁定依赖于数据库来实现锁定行为。我观察到,它在MySQL和Microsoft SQL Server中可以正常工作,但在Grails开发环境中使用的H2数据库中却不能正常工作。

一般来说
with transaction
是一种黑客行为,应该避免,主要是因为它允许您在整个代码库中散播事务性代码,而不是使用分层和分离关注点。改为使用事务服务,并根据哪些方法做什么来注释类或单个方法。净效果是相同的,因为在
withTransaction
和事务服务中使用了相同的底层Spring功能

如果没有关于代码外观和看到的错误消息的更具体信息,就很难提供帮助。如果你能重现这一点,那将大有帮助

如果并发更新的可能性不高,您通常应该尝试使用乐观锁定,并处理偶尔发生的冲突。当然,在需要的地方使用悲观锁,但不要妄想使用它们,因为它们会影响可伸缩性。正如我在另一个答案的评论中提到的,所有锁定都必须在事务中完成,否则锁将立即被释放

使用悲观锁定时,很可能会出现Hibernate乐观锁定错误/异常。如果您查看Hibernate为更新生成的SQL,它通常类似于更新集foo=?,bar=。。。其中id=?和版本=?。where子句是过度确定的——只要有id就足够了,因为它要么是对应于现有行的id,要么不是。但它会在运行该SQL之后查看JDBC更新计数,如果它为零,则
version
值必须已关闭,并且它假定这一定是由其他人编辑文件并增加版本引起的


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

是的,通常数据库功能依赖于数据库来实现。您一定做错了-H2支持锁定,甚至支持MVCC。打开SQL日志并运行类似于
Show.lock(1111)
的程序,您将看到类似于
select。。。从…起哪里对于更新
,更新的是关键部分。请注意,锁定仅在事务中有意义,因为这是您需要锁处于活动状态的时间跨度,并且事务管理器在提交或回滚时释放锁。是的,我在hibernate查询日志中看到了mysql对“for update”的锁定。但是我不知道为什么会抛出这个乐观锁定异常。非常感谢您如此快速的响应,因为我们添加了更多的详细信息。看起来异常是从缓存删除代码生成的,这是对redis的调用。在这个调用中,一个简单的redis键删除正在发生。无法理解发生此异常的原因。