【发布时间】:2014-08-11 20:29:33
【问题描述】:
我正在使用 Spring / Spring-data-JPA,发现自己需要在单元测试中手动强制提交。我的用例是我正在做一个多线程测试,其中我必须使用在产生线程之前持久化的数据。
不幸的是,鉴于测试是在 @Transactional 事务中运行的,即使是 flush 也无法让生成的线程访问它。
@Transactional
public void testAddAttachment() throws Exception{
final Contract c1 = contractDOD.getNewTransientContract(15);
contractRepository.save(c1);
// Need to commit the saveContract here, but don't know how!
em.getTransaction().commit();
List<Thread> threads = new ArrayList<>();
for( int i = 0; i < 5; i++){
final int threadNumber = i;
Thread t = new Thread( new Runnable() {
@Override
@Transactional
public void run() {
try {
// do stuff here with c1
// sleep to ensure that the thread is not finished before another thread catches up
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
threads.add(t);
t.start();
}
// have to wait for all threads to complete
for( Thread t : threads )
t.join();
// Need to validate test results. Need to be within a transaction here
Contract c2 = contractRepository.findOne(c1.getId());
}
我尝试过使用实体管理器,但这样做时收到错误消息:
org.springframework.dao.InvalidDataAccessApiUsageException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead; nested exception is java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:293)
at org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect.ajc$afterThrowing$org_springframework_orm_jpa_aspectj_JpaExceptionTranslatorAspect$1$18a1ac9(JpaExceptionTranslatorAspect.aj:33)
有没有办法提交事务并继续它?我一直找不到任何方法可以让我调用commit()。
【问题讨论】:
-
您可能会研究是否有办法让生成的线程参与事务,以便他们看到未提交的结果。
-
如果方法是
@Transactional,从方法返回提交事务。那么为什么不直接从方法中返回呢? -
从概念上讲,单元测试不应该是事务性的,而且对于 Spring 的模型,它也没有实际意义。您应该查看使用 Spring TestContext 的集成测试,它具有帮助处理事务的工具:docs.spring.io/spring/docs/3.2.x/spring-framework-reference/…
-
@JimGarrison 实际上我的单元测试的重点是测试并行事务并验证事务中没有并发问题。
-
@Raedwald 如果我从该方法返回,我该如何继续我的测试?我需要在我的线程产生之前提交,因为线程使用在它们产生之前创建的数据。
标签: java spring jpa spring-data spring-transactions