不太科学 待后续优化 在事务情况下无法实现acid
原理就是 使用工具类的时候单独得到项目环境的 SqlSessionFactory 然后用它开一个BATCH的session 然后进行操作
1 定义一个枚举类 表示我们的批处理是什么操作
public enum OpreationType { INSERT,UPDATE,DELETE }
2 写工具类
@Component public class MyBatisBatchUtil { @Autowired private List<SqlSessionFactory> sqlSessionFactoryList; public List<?> executeBatch(OpreationType opreationType,List<?> param,Class mapper,String methodName){ int size = sqlSessionFactoryList.size(); if(size>1){ throw new RuntimeException("当前项目为多数据环境 请指明具体数据库"); } String name = mapper.getName(); String id=name+"."+methodName; SqlSessionFactory sqlSessionFactory = sqlSessionFactoryList.get(0); return doOpreation(sqlSessionFactory,param,id,opreationType); } public List<?> executeBatch(OpreationType opreationType,List<?> param,Class mapper,String methodName,String sqlSessionFactoryId){ String name = mapper.getName(); String id=name+"."+methodName; SqlSessionFactory sqlSessionFactory = sqlSessionFactoryList.stream().filter(p->{ return p.getConfiguration().getEnvironment().getId().equals(sqlSessionFactoryId); }).findFirst().orElseThrow(()->new RuntimeException("找不到对应的sqlSessionFactory")); return doOpreation(sqlSessionFactory,param,id,opreationType); } private List<?> doOpreation( SqlSessionFactory sqlSessionFactory,List<?> params,String mapperId,OpreationType opreationType){ List<Object> sucessfulResult=new ArrayList<>(); SqlSession sqlSession =new SqlSessionTemplate(sqlSessionFactory,ExecutorType.BATCH); try { String mapperLocation=mapperId; switch (opreationType){ case INSERT: params.forEach(p->{ sqlSession.insert(mapperLocation, p); }); break; case DELETE: params.forEach(p->{ sqlSession.delete(mapperLocation,p); }); break; case UPDATE: params.forEach(p->{ sqlSession.update(mapperLocation,p); }); break; } List<BatchResult> batchResults = sqlSession.flushStatements(); batchResults.forEach(p->{ int[] updateCounts = p.getUpdateCounts(); sucessfulResult.addAll(Arrays.asList(updateCounts)); }); sqlSession.commit(); sqlSession.close(); } catch (Exception e){ sqlSession.rollback(); sqlSession.close(); throw new RuntimeException(e); } return sucessfulResult; } }
使用方法:如下
List<Shop> shops=new ArrayList<>(); for (int i = 1; i <=30 ; i++) { Shop shop=new Shop(); shop.setId(i); shop.setName("order"+i); shops.add(shop); } List<?> result = myBatisBatchUtil.executeBatch(OpreationType.INSERT, shops, TestMapper2.class, "insert");我的TestMapper2如下所示:
public interface TestMapper2 { int insert(Shop shop); int delete(Integer id); }
请注意此种方式也需要我们的mapper被mybatis扫描到!