【发布时间】:2021-10-14 02:20:09
【问题描述】:
我有 service-1 的方法使用 @Transactional 调用 service-2 和 service-3 方法。
现在, 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 = 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 中,Service-3 中的异常是否会影响(回滚)Service-2,因为 Service-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");
}
}
}
【问题讨论】:
标签: java spring transactions