十二,MyBatis进行批处理

本节学习利用集合保存批处理数据,再利用批处理sql(使用foreach进行遍历)一次性进行数据的批处理

一,批量新增

  1. xml进行配置
<!--    INSERT INTO table-->
<!--    VALUES ("a1","a2","a3"),("b1","b2","b3"),(...)-->
<!--批量新增-->
<!--因为批处理是一次性导入多条,所以这里使用list-->
<!--foreach类似for循环 collection:迭代的数据源,固定写入list,表示从外界传入的list集合 ,item;循环中的迭代变量
,item:索引,类似于数字,seperator:分割符号-->
<insert id="batchInsert" parameterType="java.util.List">
    insert into t_goods(title,sub_title,original_cost,current_price,discount,is_free_delivery,category_id)
    values
    <foreach collection="list" item="item" index="index" separator=",">
        (#{item.title},#{item.subTitle},#{item.originalCost},#{item.currentPrice},#{item.discount},#{item.isFreeDelivery},#{item.categoryId})
    </foreach>
</insert>
  1. 测试
@Test
public void testBatchInsert() {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        List<Goods> good = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
    
    
            Goods goods = new Goods();
            goods.setTitle("测试商品6");
            goods.setSubTitle("测试商品666");
            goods.setCategoryId(111);
            goods.setOriginalCost(1000f);
            goods.setIsFreeDelivery(1);
            goods.setDiscount(2f);
            goods.setCurrentPrice(300f);
            good.add(goods);
        }
        sqlSession.insert("goods.batchInsert",good);
        sqlSession.commit();
    } catch (Exception e) {
    
    
        if (sqlSession != null) {
    
    
            sqlSession.rollback();
        }
        throw e;
    } finally {
    
    
       MyBatisUtils.closeSqlSession(sqlSession);
    }
}

二,批量删除

  1. xml进行配置
<!-- DELETE FROM table where goods_id in(a,b)-->
<!--批量删除-->
<!--这里只需要传入item即可,因为它只是goods编号-->
<!--open和close指代删除语句in后面的左右括号-->
<delete id="batchDelete" parameterType="java.util.List">
    delete from t_goods where goods_id in
    <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
        (#{item})
    </foreach>
</delete>
  1. 测试
@Test
public void testBatchDelete() {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        List<Integer> good = new ArrayList<>();
        good.add(10000);
        good.add(10001);
        sqlSession.delete("goods.batchDelete",good);
        sqlSession.commit();
    } catch (Exception e) {
    
    
        if (sqlSession != null) {
    
    
            sqlSession.rollback();
        }
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSqlSession(sqlSession);
    }
}

三,批量插入数据的局限

  1. 无法获取插入数据的id,如果要通过id做后续处理就不合适了
  2. 批量生成的sql太长,可能会被服务器拒绝(解决方案:可以采用分段形式,比如要导入100w条数据,可以通过for循环二次嵌套完成,一次导入1w条)

猜你喜欢

转载自blog.csdn.net/qq_36792120/article/details/112500855