我有service-1的方法调用service-2和service-3的方法使用@Transactional。
现在,Scenario_1 (工作场景):
Service-1:
@Transactional
void m1() {
m2(); // of Service 2
m3(); // of Service 3
}
Service-2:
@Transactional(propagation = Propagation.REQUIRES_NEW)
void m2() {
//1. Insert Employee
}
Service-3:
@Transactional
void m3() {
// 1. Insert Insurance
// 2. Throw RuntimeException
}
Result:
1. Employee inserted
2. Insurance object not inserted (i.e. rolled back)Scenario_2 (未得到预期结果):(将“传播= Propagation.REQUIRES_NEW”放在Service-3方法中而不是在Service-2方法中)
Service-2:
@Transactional
void m2() {
//1. Insert Employee
}
Service-3:
@Transactional(propagation = Propagation.REQUIRES_NEW)
void m3() {
// 1. Insert Insurance
// 2. Throw RuntimeException
}
Result:
1. Employee not inserted (why ?)
2. Insurance not inserted (i.e. rolled back)在Scenario_2中,服务-3中的异常是否会影响(回滚)服务-2,因为服务-3正在新事务中运行?我的理解是正确的还是我遗漏了什么?请建议一下。
以下是供参考的实际文件(工作方案):
1. OrganzationServiceImpl.java
@Service
public class OrganzationServiceImpl implements OrganizationService {
@Autowired
EmployeeService employeeService;
@Autowired
HealthInsuranceService healthInsuranceService;
@Transactional
@Override
public void joinOrganization(Employee employee, EmployeeHealthInsurance employeeHealthInsurance) {
employeeService.insertEmployee(employee);
healthInsuranceService.registerEmployeeHealthInsurance(employeeHealthInsurance);
}
}
2. EmployeeServiceImpl.java
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeDao employeeDao;
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public void insertEmployee(Employee employee) {
employeeDao.insertEmployee(employee);
}
}
3. HealthInsuranceServiceImpl.java
@Service
public class HealthInsuranceServiceImpl implements HealthInsuranceService {
@Autowired
HealthInsuranceDao healthInsuranceDao;
@Transactional
@Override
public void registerEmployeeHealthInsurance(EmployeeHealthInsurance employeeHealthInsurance) {
healthInsuranceDao.registerEmployeeHealthInsurance(employeeHealthInsurance);
if (employeeHealthInsurance.getEmpId().equals("emp1")) {
throw new RuntimeException("thowing RuntimeException for testing");
}
}
}发布于 2021-08-10 14:05:24
在我的理解中,问题是在场景2中,来自Service-1的事务也会被回滚,因为您不处理Service-3中的RuntimeException。由于Service-2在此场景中与Service-2在相同的事务中,所以员工插入将回滚。这在场景1中不会发生,因为您有一个单独的服务-2事务。
https://stackoverflow.com/questions/68728157
复制相似问题