我在调试和诊断应用程序中的问题时遇到了困难。
我有一个连接到 JPA 事件侦听器以在POST_COMMIT_INSERT
. 执行的工作也是事务性的。
我在编写一个捕获事务后事务中发生的工作的测试时遇到了困难。
我当前的测试在方法中执行它的断言@PostTransaction
。但是,尽管我看到数据被持久化(使用日志语句),但我无法使用 postTransaction-transaction 工作。
我怀疑这是因为在我的@PostTransaction
方法中,我还为时过早——而且还有另一笔交易正在进行中。
这是一个大致演示该场景的示例:
创建并保存 a后
Foo
,创建并保存Bar
.
// Step 1. The factory that responds to creation of the Foo, and build a bar.
@Component
class BarFactory implements PostInsertEventListener
{
// Note: I've tried various versions of @Transactional on different points
// within this class, and none have worked.
@Autowired
private BarRepository repository;
@Override
public void onPostInsert(PostInsertEvent event)
{
if (event.getEntity() instanceof Foo)
{
createBar();
}
}
@Transactional
public createBar()
{
Bar bar = new Bar();
repository.save(bar);
log.info("Bar was created: " + bar.getId());
}
}
// Step 2: Register the BarFactory
@Component
class LifecycleListenerFactory {
// This is a spring bean, and the listeners are also spring beans
// so we have to use a somewhat long-winded approach to register them
// with the EntityManager
@Autowired
public LifecycleListenerFactory(EntityManager em, BarFactory barFactory)
{
SessionFactory sessionFactory = getSessionFactory(em);
EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
EventListenerGroup<PostInsertEventListener> eventListenerGroup = registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT);
eventListenerGroup.appendListener(barFactory);
}
SessionFactory getSessionFactory(EntityManager entityManager) {
Session session = (Session) entityManager.getDelegate();
SessionFactory sessionFactory = session.getSessionFactory();
return sessionFactory;
}
}
// Step 3: Test.
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@TransactionConfiguration(defaultRollback=false)
class MyTest {
@Autowired
private FooRepository fooRepo;
@Autowired
private BarRepository barRepo;
@Test
public void test()
{
fooRepo.save(new Foo());
}
@AfterTransaction
public void assert()
{
assertThat(barRepo.findAll().size(),equalTo(1));
}
}
在这种情况下,我看到以下输出:
INFO: Bar was created: 1
但是测试失败了。
我的假设是正确的,即我@AfterTransaction
在错误的交易之后运行,还是这里有其他问题?
如果是这样,我该如何测试?
我尝试在@Transaction
中移动边界BarFactory
,但这没有任何效果。