【问题标题】:Is there a way to refresh the entity value in hibernate/grails without refreshing from the database有没有办法刷新hibernate/grails中的实体值而不刷新数据库
【发布时间】:2016-12-14 18:48:18
【问题描述】:

(我将在示例中使用 Groovy/Grails 语法)

在休眠时加载实体时,它们会保存在会话缓存/L1 中,问题是如果在会话之外更改它们不会被引用,即使我通过 GORM 方法重新查询它们。这就是我使用 refresh() 的原因。

(以下所有操作都在一个会话中完成。)

User.withNewTransaction {
  User user = User.findById(1L, [lock: true]) //select for update
  user.name='new name' 
  user.save()
}

//user entity gets updated on a different thread.

User.withNewTransaction {
  user = User.findById(1L, [lock: true]) //another select for update
  //at this point, the user entity is not yet filled in with the updated values from the different thread
  //so I'm forced to do a refresh so that the user will have the correct values
  user.refresh()
  //update user
}

是否有替代方案?

这意味着我必须查询两次以确保我们在第二笔交易中获得正确的值。

【问题讨论】:

    标签: hibernate grails


    【解决方案1】:

    是的。

    只需删除refresh

    User.withNewTransaction {
      user = User.findById(1L) //user = User.findById(1L, [lock: true]) //another select for update
      //at this point, the user entity is not yet filled in with the updated values from the different thread
      //so I'm forced to do a refresh so that the user will have the correct values
      //user.refresh()
      //update user
    }
    

    更好的解决方案是放弃交易!因为事务用于批处理操作:

    user = User.findById(1L)
    

    如果您希望保留事务语法,那么使用withTransaction 将其加入其他正在进行的事务 会更有意义:

    User.withTransaction {
          user = User.findById(1L) //user = User.findById(1L, [lock: true]) //another select for update
          //at this point, the user entity is not yet filled in with the updated values from the different thread
          //so I'm forced to do a refresh so that the user will have the correct values
          //user.refresh()
          //update user
        }
    

    夏天:

    你应该很少使用refresh,因为它忽略了休眠的优势,除非有特殊需要指定here

    【讨论】:

    • 如果我删除刷新调用,用户的值可能会变得陈旧。由于其他线程可能对其进行修改。由于某种要求,我必须使用交易块。
    • 我们需要锁定,这样其他线程就不会触及我们当前正在修改的实体。关于与锁定和直接获取混合,我不确定我是否理解。你的意思是跳过休眠并只使用本机sql吗?可以详细介绍一下吗?
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多