核心:通过设置使用的链接自动提交为false,发生错误/结果不符合预期就手动回滚
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
@Slf4j
@RequiredArgsConstructor
public class PlanGoodsExtendFeignImpl implements PlanGoodsExtendFeign {
// 获取数据库连接,获取会话(内部自有事务)
private final SqlSessionFactory sqlSessionFactory;
// 注入线程池
private final ExecutorService planGoodsExtendThreadPool;
@Override
public void test() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession(sqlSessionFactory);
Connection connection = sqlSession.getConnection();
try {
// 设置手动提交
connection.setAutoCommit(false);
SpecialGoodsErrorMapper specialGoodsErrorMapper = sqlSession.getMapper(SpecialGoodsErrorMapper.class);
//先做删除操作
specialGoodsErrorMapper.delete(null);
//模拟数据
List<Callable<Integer>> callableList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
SpecialGoodsError specialGoodsError = new SpecialGoodsError();
specialGoodsError.setProductSelectedId((long) i);
specialGoodsError.setImportVersion((long) i);
specialGoodsError.setCode(i + "");
specialGoodsError.setMessage(i + "");
Callable<Integer> callable = () -> specialGoodsErrorMapper.insert(specialGoodsError);
callableList.add(callable);
}
//测试报错
// Callable<Integer> callable = () -> {
// return 1 / 0;
// };
// callableList.add(callable);
//执行子线程
List<Future<Integer>> futures = planGoodsExtendThreadPool.invokeAll(callableList);
for (Future<Integer> future : futures) {
if (future.get() <= 0) {
connection.rollback();
return;
}
}
//符合预期则手动提交
connection.commit();
System.out.println("添加完毕");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
log.info("error", e);
throw new RuntimeException("出现异常");
}
}
}