我有一个方法的服务,该方法没有用 @Transactional
进行注解:
@Service
@RequiredArgsConstructor
public class MainService {
private final ServiceA serviceA;
public void processData() {
List<EntityA> list = serviceA.getList();
list.forEach(item -> {
try {
serviceA.doSomeDbOperations(item);
} catch(Exception e) {
// some processing here
} finally {
// some processing and DB interactions here
}
})
}
}
如果try块中发生异常,目的是回滚所做的更改(serviceA.doSomeDbOperations(item)
)。因此,我在ServiceA中用@Transactional
注释了这个方法:
@Service
public class ServiceA {
// dependencies
@Transactional
public void doSomeDbOperations(EntityA item) {
// some logic here
repositoryA.save(item)
serviceB.deleteSomething(input)
}
}
serviceB.deleteSomething(input)
可能会抛出异常:
@Service
public class ServiceB {
// dependencies
public void deleteSomething(EntityA item) {
// some logic here
if(condition) {
Throw new RuntimeException();
}
}
}
问题在于当抛出异常时,try块中所做的更改不会回滚,数据不一致。你有什么想法吗?