안녕하세요, 우리는 @Transactional
인 메인 서비스 메소드, @Transactional
인 다른 컴포넌트의 메소드를 호출하지만 propagation = Propagation.REQUIRES_NEW <가있는 계층 구조가 있습니다. / code>.
Bar
중 하나가 실패하면 다른 엔티티가 저장되도록 할 이유가 있습니다. 문제는이 논리를 테스트하기 위해 foo 엔티티를 준비 할 때입니다. 중첩 된 트랜잭션에 대해 준비된 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()));
}