hibernate - Grails:测试乐观锁定

标签 hibernate grails grails-orm

使用 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 照常保存)。

我做错了什么吗?

最佳答案

您的方法存在的问题是 groupAgroupB 引用相同的托管(附加到 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/

相关文章:

java - Spring MessageSource 中验证消息的动态表达式变量

java - 在 SessionFactory 中获取 NullPointerException

grails - 在Grails 2.4.4中进行调试。 IDE Groovy/Grails工具套件

oracle - 如何在 HQL 查询中使用 native sql 函数?

grails - 在 grails 域类中声明排序关联的最佳方法是什么?

hibernate - 为 hibernate 中的唯一约束添加自定义消息

java - 在 JPA 中映射具有复合外键的实体

在 Ubuntu 上运行应用程序时出现 Grails 依赖错误

postgresql - Grails 字节数组和 PostgreSQL

grails - 获取仅属于特定类别列表的关联结果