代码如下
/**
* 删除部分满足条件的用户
* 新增部分用户 由于新增数量较大,改为分批次新增
*/
@Transactional(rollbackFor = Exception.class)
public void transactionFailure(List<User> users) throws Exception{
if(!CollectionUtils.isEmpty(users)) {
this.deleteSomeUser();
//批量插入数据
int batchSize = 1000;
int length = users.size();
int i = 0;
while (length > batchSize) {
this.baseMapper.batchInsertUser(users.subList(i, i + batchSize));
i = i + batchSize;
length = length - batchSize;
}
if (length > 0) {
this.baseMapper.batchInsertUser(users.subList(i, i + length));
}
}
}
/**
* 删除部分用户
*/
public void deleteSomeUser();() {
this.baseMapper.deleteSomeUser();
}
执行发现:当这段代码抛出异常时,事务并没有回滚
调整后的代码
/**
* 删除部分满足条件的用户
* 新增部门用户 由于新增数量较大,改为分批次新增
*/
@Transactional(rollbackFor = Exception.class)
public void transactionFailure(List<User> users) throws Exception{
if(!CollectionUtils.isEmpty(users)) {
this.deleteSomeUser();
//批量插入数据
this.insertBatchRename(users);
}
}
@Transactional(rollbackFor = Exception.class)
public void insertBatchRename(List<User> users) throws Exception{
//批量插入数据
int batchSize = 1000;
int length = users.size();
int i = 0;
while (length > batchSize) {
this.baseMapper.batchInsertUser(users.subList(i, i + batchSize));
i = i + batchSize;
length = length - batchSize;
}
if (length > 0) {
this.baseMapper.batchInsertUser(users.subList(i, i + length));
}
}
/**
* 删除部分用户
*/
public void deleteSomeUser();() {
this.baseMapper.deleteSomeUser();
}
将分批次新增的代码单独放在一个事务中执行即可!!!