【发布时间】:2020-10-21 23:22:35
【问题描述】:
您好,我们有层次结构,其中主要服务方法是@Transactional,另一个组件的调用方法也是@Transactional,但使用propagation = Propagation.REQUIRES_NEW。如果Bar 之一失败,它有理由确保其他实体将保存。问题是当我们准备 foo 实体来测试这个逻辑时。对于该嵌套事务,Prepared Foo 实体不可见。你能给我建议如何解决它吗?
我们的测试:
@Transactional
@ExtendWith(SpringExtension.class)
@SpringBootTest
class MainServiceImplTest {
@Autowired
private MainServiceImpl mainService;
@Autowired
private BarRepository barRepository;
@Autowired
private FooRepository fooRepository;
@BeforeEach
public void prepareFoos() {
fooRepository.saveAndFlush(new FooEntity());
fooRepository.saveAndFlush(new FooEntity());
}
@Test
public void createBarsForAllFoosTest() {
mainService.createBarsForFoos();
Assertions.assertThat(barRepository.findAll()).hasSize(2); // failed - zero bars was saved
}
}
以及我们的服务: 主要服务方式:
@Transactional
public void createBarsForFoos() {
fooRepository.findAll().stream().forEach(fooEntity -> {
try {
nestedService.createBarForFoo(fooEntity.getId());
} catch (Exception ex) {
log.error("Saving of bar for foo with id {} failed.", fooEntity.getId());
}
});
}
以及带有新事务的嵌套服务:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void createBarForFoo(Long fooId) {
Optional<FooEntity> fooOpt = fooRepository.findById(fooId);
if (!fooOpt.isPresent()) {
log.error("There is no foo with id {}", fooId);
return;
}
barRepository.save(new BarEntity(fooOpt.get()));
}
【问题讨论】:
标签: spring spring-boot spring-data-jpa spring-transactions