JPA EntityManager在@Transactional方法之后阻塞

时间:2014-08-11 17:09:22

标签: java spring jpa junit transactions

我有一个Spring-JUnit测试,其中的安装方法使用JPA实体来设置测试数据。在测试本身中,遗留代码使用JDBC-Templates来查询插入的测试数据。当遗留代码发出查询时,对jdbcTemplate.query(...)的调用将挂起。

我的单元测试看起来像这样:

@TransactionConfiguration(defaultRollback = false)
@ContextConfiguration(locations = { "/testContext.xml" })
@Transactional
public class MyTest {

    @PersistenceContext(unitName = "someUnit")
    private EntityManager entityManager;

    @Test
    public void test() {
        // here some legacy Code is called that uses JDBC Templates to query 
        // the inserted test data. The legacy code hangs upon jdbcTemplate.query(...)
    }

    @Before 
    public void before() {
        this.entityManager.persist(new Entity1(...));
        this.entityManager.persist(new Entity2(...));
    }

}

我的问题是:为什么enitymanager在退出before()方法时没有提交?或者它是否提交并立即启动仍然引用存储实体的新事务?我还试着没有junit注释@Before注释并手动调用before()方法。但是这给出了相同的结果。

非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

测试类

@ContextConfiguration(locations = { "/testContext.xml" })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class MyTest extends AbstractTransactionalJUnit4SpringContextTests{

    @PersistenceContext(unitName = "someUnit")
    private EntityManager entityManager;

    @Autowired
    private BeforeService beforeService;

    @Test
    public void test() {
        beforeService.before();
        // here some legacy Code is called that uses JDBC Templates to query 
        // the inserted test data. The legacy code hangs upon jdbcTemplate.query(...)
    }

}

服务前

public class BeforeService {

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(final EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void before() {
        entityManager.persist(new Entity1(...));
        entityManager.persist(new Entity2(...));
    }
}

我希望我已经向你提供了有关你问题的所有答案。