【问题标题】:Force 'reload' of JPA EntityManager in integration test在集成测试中强制“重新加载”JPA EntityManager
【发布时间】:2011-07-22 11:59:42
【问题描述】:

在启用 Spring 的集成测试中,我需要强制 EntityManager 从数据库中重新读取。

@Test
@DataSet("/xml/dbunit/truncate-tables.xml")
public void createTerminalFromQuery() {

    // there should be zero terminals in the empty database
    Assert.assertEquals(0, terminalService.countTerminals());

    // makes remote REST call updating database outside the application's EntityManager
    HttpEntity<QueryResponse> result = simulateRequest("query");

    // attempts to force re-read of updated database (unsuccessfully)
    entityManagerService.getEntityManager().flush();

    // there should be exactly one Terminal in the database
    Assert.assertTrue(terminalService.existsTerminalBySerialNumber(EXISTING_TERMINAL_SERIAL_NUMBER));

}

已验证终端已创建并存在于数据库中。尽管如此,第二个断言失败了。当第一个断言被注释掉后,第二个就OK了。

测试框架是 Unitils/DBUnit,通过 @PersistenceContext 注入 EntityManager 很困难,因为所需的包 unitils-orm 依赖于 Spring 2.5 和 JPA 1.0 导致其他问题。

相反,我创建了 EntityManagerService 并验证它确实使用与 TerminalService 相同的 EntityManager。

我已经尝试过 EntityManager.clear() 和 flush() 并从 EntityManagerFactory 中逐出缓存 - 但似乎没有任何效果。

有什么建议吗?

【问题讨论】:

    标签: jpa entitymanager


    【解决方案1】:

    尚不清楚您如何管理交易。由于clear() 没有帮助,可能两个检查都在同一个事务中执行,而该事务看不到 REST 服务提交的事务结果。

    尝试在不同的事务中执行检查。

    【讨论】:

    • 被调用服务中的事务由Spring处理,但我对事务的理解很基础。如何确保两个断言在不同的事务中执行?我尝试使用 @Transactional Propagation.REQUIRES_NEW 将每个断言包装在其自己的私有方法中(绝望地尝试强制提交/重新加载/刷新),但这也没有效果。
    • @morsor:我不太明白您的EntityManagerService 如何与 Spring 管理的事务交互。如果是手动创建EntityManagers,可能跟Spring管理的事务无关,需要手动调用EntityManagers的方法来控制事务。
    • EntityManagerService 使用@PersistenceContext 绑定与Terminalservice 相同的EntityManager。这两个服务都是托管的 Spring bean。
    • 您是说我应该在集成测试中以编程方式处理事务吗?
    • 原来集成测试中的事务由测试框架 Unitils 隐式处理,直到我用 @Transactional(value = TransactionMode.DISABLED) 注释这些方法。这解决了我的直接问题并引起了一些新问题:-) 感谢您为我指明正确的方向
    猜你喜欢
    • 2012-06-18
    • 2013-02-11
    • 2015-09-02
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多