在我最近的项目中,我遇到一个场景,当嵌套方法中发生错误时,我需要回滚数据库操作。之前我曾与@Transactional
合作使用单一方法。那个时候效果很好。但是在当前情况下,我依赖于另一种方法。因此,当发生错误时,我需要回滚嵌套方法。我想用这种方法回滚
@Transactional
@Override
public String updateCustomOfficeHour(OfficeHour officeHour) {
if (officeHour.getId() == null || officeHourRepository.getFirstById(officeHour.getId()) == null)
throw new EntityNotFoundException("No Office-Hour found with this id");
OfficeHour temp = officeHourRepository.getFirstById(officeHour.getId());
List<OfficeHour> officeHours = officeHourRepository.findByFromDateAndToDate(temp.getFromDate(), temp.getToDate());
List<OfficeHour> tempList = new ArrayList<>();
for (OfficeHour officeHourObj : officeHours) {
officeHourObj.setDeleted(true);
tempList.add(officeHourObj);
}
officeHourRepository.saveAll(tempList);
this.createCustomOfficeHour(officeHour);
return "Updated Custom-Office-Hour";
}
我在officeHourRepository.saveAll(tempList);
行有数据库操作
当方法this.createCustomOfficeHour(officeHour);
中发生错误时,我需要回滚。此方法是
@Transactional
@Override
public String createCustomOfficeHour(OfficeHour officeHour) {
if (officeHour.getFromDate() == null || officeHour.getToDate() == null
|| officeHour.getFirstOutTime() == null || officeHour.getLastInTime() == null
|| officeHour.getInTime() == null || officeHour.getOutTime() == null)
throw new EntityNotFoundException("Null value received for OfficeHour fields!");
if (officeHour.getToDate().compareTo(officeHour.getFromDate()) < 0)
throw new EntityNotFoundException("FromDate is Getter than ToDate");
if (officeHourRepository.isFromDateExist(officeHour.getFromDate()).longValue() > 0
|| officeHourRepository.isToDateExist(officeHour.getToDate()).longValue() > 0) {
throw new EntityNotFoundException("FromDate/ToDate is already assigned");
}
if (officeHourRepository.isDateExistsBetweenFromAndToDate(officeHour.getFromDate(), officeHour.getToDate()).longValue() > 0)
throw new EntityNotFoundException("Office Hour Already Assigned In This Range");
for (int i = 1; i <= count; i++) {
........
........
........
officeHourRepository.save(obj);
}
return "Custom Office-Hour Created";
}
这是我的Exception
班
public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(String message) {
super(message);
}
}
我还在spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
中添加了application.properties
任何帮助将不胜感激。
答案 0 :(得分:0)
您的EntityNotFoundException
是未经检查的异常,遵循spring docs:
用于声明式事务管理的Spring默认行为如下 EJB约定(仅在未检查的异常时自动回滚)
默认情况下,交易应回滚。
这是因为updateCustomOfficeHour
和createCustomOfficeHour
是在同一事务下处理的(此处没有覆盖传播,因此使用默认的REQUIRED)。
您可以在updateCustomOfficeHour
方法上为您的异常添加显式回滚,但是无论如何这应该是多余的:
@Transactional(rollbackFor = {EntityNotFoundException.class})