SpringBoot项目事务管理
在Application主方法上添加@EnableTransactionManagement注解来启用事务的管理
@SpringBootApplication
@ComponentScan(basePackages = {"com.spring.**"})
@EnableTransactionManagement
@EnableConfigurationProperties({
FileStorageProperties.class
})
public class SpringApplication {
public static void main(String[] args) {
SpringApplication.run(SpringApplication.class, args);
}
}
多数据源事务管理
当一个项目有多个数据源是,当对该项目进行事务管理时会报错。
需要对多个数据源设置“主从”事务管理器,使用@Primary注解来表示主事务管理器,如果是需要使用“从事务管理器”则需要在事务管理的方法的@Transactional中添加属性指定事务管理器
@Transactional(rollbackFor = Exception.class,transactionManager = "EztxManager" )
数据源配置
查看springboot双数据源配置。
在需要进行事务管理的方法上添加@Transactional注解
自动回滚
因为springboot默认的事务规则是遇到运行异常(RuntimeException)和程序错误(Error)才会回滚,如果需要抛出“自定义异常”则需要在@Transactional注解中使用rollbackFor属性指定异常,@Transactional(rollbackFor = Exception.class)
手动回滚
//手动回滚异常
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
代码实例
Application
@SpringBootApplication
@ComponentScan(basePackages = {"com.spring.**"})
@EnableTransactionManagement
@EnableConfigurationProperties({
FileStorageProperties.class
})
public class SpringApplication {
public static void main(String[] args) {
SpringApplication.run(SpringApplication.class, args);
}
}
Controller层
@PostMapping("/import")
@ApiOperation(value = "解析数据",notes = "解析",httpMethod = "POST")
public Response import(@RequestParam("file")MultipartFile file) {
return new Response.Builder()
.withResult(excelService.analyzeData(file))
.build();
}
Service层
@Transactional(rollbackFor = Exception.class)
public List<String> analyzeData(MultipartFile file) {
try(InputStream stream = file.getInputStream()) {
Workbook wb = new XSSFWorkbook(stream);
Sheet sheet = wb.getSheetAt(0);
List<ThermFactoryPO> list = new ArrayList<>();
int firstRowIndex = sheet.getFirstRowNum() + 1;
int lastRowIndex = sheet.getLastRowNum();
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
Row row = sheet.getRow(rIndex);
if (row != null) {
ThermFactoryPO thermFactoryPO = new ThermFactoryPO();
ArrayList<String> strings = new ArrayList<>();
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
Cell cell = row.getCell(cIndex);
if (cell.getCellType() == CellType.STRING) {
strings.add(cell.toString());
} else if (cell.getCellType() == CellType.NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strings.add(simpleDateFormat.format(cell.getDateCellValue()));
} else {
long numericCellValue = (long)cell.getNumericCellValue();
strings.add(numericCellValue + "");
}
}
}
thermFactoryPO.setImportTime(simpleDateFormat1.format(System.currentTimeMillis()));
thermFactoryPO.setThermId(strings.get(0));
thermFactoryPO.setModel(strings.get(1));
thermFactoryPO.setSsid(strings.get(2));
thermFactoryPO.setFactory(strings.get(3));
thermFactoryPO.setDeliveryTime(strings.get(4));
thermFactoryPO.setThermMac(strings.get(5));
thermFactoryPO.setPassword(strings.get(6));
thermFactoryPO.setSocketurl(strings.get(7));
thermFactoryPO.setLiences(strings.get(8));
list.add(thermFactoryPO);
}
}
excelDAO.save(list);
List<String> thermIds = excelDAO.getIds();
if (thermIds.size() != 0){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return thermIds;
}else {
return new ArrayList<String>();
}
} catch (IOException e) {
log.error("file parse error:{}", e.getMessage());
}
return null;
}
dao层
/**
* 保存表格信息
* @param list
* @return
*/
int save(@Param("list") List<ThermFactoryPO> list);
/**
* 判断导入数据,是否重复
* @param
* @return
*/
List<String> getIds();
mapper文件
<insert id="save" parameterType="com.hrzn.dao.hradminpo.ThermFactoryPO" >
INSERT INTO thermostatfactory(therm_id,therm_mac,model,ssid,password,factory,delivery_time,import_time,socketurl,liences) VALUES
<foreach collection="list" item="factoryPO" separator=",">
(#{factoryPO.thermId},#{factoryPO.thermMac},#{factoryPO.model},#{factoryPO.ssid},#{factoryPO.password},#{factoryPO.factory},#{factoryPO.deliveryTime},#{factoryPO.importTime},#{factoryPO.socketurl},#{factoryPO.liences})
</foreach>
</insert>
<select id="getIds" resultType="java.lang.String">
select therm_id from thermostatfactory group by therm_id having count(therm_id) >1;
</select>