- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 Grails 2.3.9
我目前正在尝试测试 Grails 中的乐观锁定。 documentation说,
When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a StaleObjectException
在集成测试中,我有类似的东西:
def existingGroup = new Group("Group")
.save(flush: true, failOnError: true)
def groupA = Group.get(existingGroup.id)
def groupB = Group.get(existingGroup.id)
groupA.name = "Group A"
groupA.save(failOnError: true, flush: true)
groupB.name = "Group B"
groupB.save(failOnError: true, flush: true)
但是,永远不会抛出异常。所以,我想,我在 session /冲洗方面做错了。但是所有排列(使用 flush 而不是)都没有改变。我希望看到抛出此异常。
我也尝试将版本重置为 0,但没有成功(groupB 照常保存)。
我做错了什么吗?
最佳答案
您的方法存在的问题是 groupA
和 groupB
引用相同的托管(附加到 hibernate session )域对象。
如果在 groupA.save()
之后打印版本,您可以看到 groupB
的版本也发生了变化。
您可以通过手动创建新事务来创建乐观锁定错误:
def groupA = Group.get(123)
Group.withNewTransaction {
def groupB = Group.get(123)
groupB.name = "Group B"
groupB.save(failOnError: true, flush: true)
}
groupA.name = "Group A"
groupA.save(failOnError: true, flush: true) // should fail
这里 groupB
在另一个事务中被检索、修改和提交。 groupA
仍然使用旧版本,因此对 groupA
的保存操作应该会失败。
请注意,您必须使用 withNewTransaction
而不是 withTransaction
。使用 withTransaction
创建的事务将参与用于集成测试的事务。因此,行为与没有任何手动交易 block 的行为相同。
关于hibernate - Grails:测试乐观锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24031590/
我正在编写一个 Web 应用程序,两个不同的用户可以在其中更新事物列表,例如待办事项列表。我已经意识到,乐观锁定机制效果最好,因为我不希望出现高争用情况。 我一直在查看事务隔离级别,现在我有点困惑。看
这个问题在这里已经有了答案: Pessimistic versus Optimistic Concurrency (Locking versus Feedback) (3 个答案) 关闭 8 年前。
我是一名优秀的程序员,十分优秀!