spring在集成测试中启动并行事务

vic*_*tor 6 spring integration-testing hibernate spring-transactions

我一直在寻找解决方案,但似乎找不到一个好的解决方案.我有一个复杂的场景,我想评估hibernate 乐观锁定与悲观锁定的行为

这样做的最佳位置是在一组良好的集成测试中,但我似乎无法找到一种简单的方法来启动并行事务.

  • 如何在Spring集成测试中创建2个并行事务,而无需手动创建Threads并注入SessionFactory对象.

请注意,我还没有找到一种方法来创建2个并行事务而不会产生至少2个线程(也许有一种方法,我希望你能告诉我一个例子).

Aug*_*sto 3

添加此作为答案,因为评论空间不足:

过去,我通过创建不同的 EntityManager/Session 然后注入它们来在 vanilla Spring 上进行测试。我不确定如何通过 Spring 集成测试来做到这一点,但它可能会激发一个想法。

在下面的代码中,Account 是一个带有版本控制的小对象。如果可以使用自定义实体管理器实例化 Spring Integration 流程(或任何调用的内容),您也可以实现相同的目标。

public void shouldThrowOptimisticLockException() {
      EntityManager em1 = emf().createEntityManager();
      EntityManager em2 = emf().createEntityManager();
      EntityTransaction tx1 = em1.getTransaction();
      tx1.begin();

      Account account = new Account();
      account.setName("Jack");
      account.updateAudit("Tim");

      em1.persist(account);
      tx1.commit();


      tx1.begin();
      Account account1 = em1.find(Account.class, 1L);
      account1.setName("Peter");

      EntityTransaction tx2 = em2.getTransaction();
      tx2.begin();
      Account account2 = em2.find(Account.class, 1L);
      account2.setName("Clark");

      tx2.commit();
      em2.close();

      tx1.commit(); //exception is thrown here
      em1.close();
}
Run Code Online (Sandbox Code Playgroud)