spring中事务控制标签@Transactional的问题
我想在Service中进行事务控制,就是如果抛异常了则将前面插入的数据回滚.但是我下面这个代码好像不能实现这个功能.
我对Transactional的了解不深,希望大佬帮忙指定一二 .代码如下
@Transactional
public Object importExcel(MultipartFile uploadFile) throws Exception {
//TODO: 事务控制未完成,导入失败时前面的数据也会导入
InputStream inputStream = uploadFile.getInputStream();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
List<SampleUsed> sampleUsedList = null;
// 工作簿
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// 读取工作表
XSSFSheet sheet = workbook.getSheetAt(0);
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
XSSFRow row = sheet.getRow(i);
try {
InsertSampleUsed(11, row, i);
} catch (Exception e) {
System.out.println( e.getMessage());
return new ErrorTip(500, "表中第" + (i + 1) + "行有错,"+e.getMessage());
}
}
return new SuccessTip();
}
public void InsertSampleUsed(int i, XSSFRow row, int rownum) throws Exception {
XSSFCell cell = row.getCell(i);
if (cell != null && cell.toString().trim() != "") {
SampleUsed sampleUsed = new SampleUsed();
sampleUsed.setUserName(cell.toString().trim());
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
String value = row.getCell(1).getStringCellValue();
Integer sampleId = sampleDao.getSampleIdByLabCode(value);
if (sampleId == null) {
throw new RuntimeException("表中的实验室编码有错,查无此样本");
}
sampleUsed.setSampleId(sampleId);
Cell useDate = row.getCell(i + 1);
if (useDate == null||useDate.toString().trim().equals("")) {
throw new RuntimeException("使用日期不能为空");
}
Date d = useDate.getDateCellValue();
sampleUsed.setUseDate(d);
Cell returnDate = row.getCell(i + 2);
if (returnDate != null && returnDate.toString().trim() != "") {
Date returnDate1 = returnDate.getDateCellValue();
sampleUsed.setReturnDate(returnDate1);
}
if (row.getCell(10) != null && row.getCell(10).toString().trim() != "") {
row.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
sampleUsed.setRemarks(row.getCell(10).getStringCellValue());
}
sampleUsedDao.insert(sampleUsed);
if (i > 20) {
return;
}
InsertSampleUsed(i + 3, row, rownum);
}
}