怎么提交java源代码_java – 如何在@Transactional方法中手动强制提交?

参见英文答案 >

How to flush data into db inside active spring transaction?

我使用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 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()的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值