【发布时间】:2019-08-24 18:37:54
【问题描述】:
在我最近的项目中,我遇到了一个场景,当嵌套方法发生错误时,我需要回滚数据库操作。早些时候我在单一方法上使用@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);
}
}
我还在application.properties中添加了spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
任何帮助将不胜感激。
【问题讨论】:
标签: java mysql hibernate spring-boot transactional