Mybatis批处理

批量插入数据

<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},
        #{currentPrice},#{discount},#{isFreeDelivery},#{categoryId})
    </foreach>
</insert>
    @Test
    public void testBatchInsert(){
        SqlSession sqlSession=null;
        try{
            sqlSession=MyBatisUtils.openSession();
            List<Goods> list=new ArrayList();
            for(int i=0;i<10000;i++){
                Goods goods = new Goods();
                goods.setTitle("");
                //goods.set...();
                goods.setCategoryId(43);

                list.add(goods);
            }
            sqlSession.insert("goods.batchInsert",list);
            sqlSession.commit();
        }catch (Exception e){
            if(sqlSession!=null){
                sqlSession.rollback();
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

 批量插入数据的局限:

  1.无法获得插入数据的id  2.批量生成的SQL太长,可能会被服务器拒绝

批量删除

 

<delete id="batchDelete" parameterType="java.util.List">
    delete t_goods where goods_id in
    <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
        #{item}
    </foreach>
</delete>
    @Test
    public void testBatchDelete(){
        SqlSession sqlSession=null;
        try{
            sqlSession=MyBatisUtils.openSession();
            List list=new ArrayList();
            list.add(1920);
            list.add(1921);
            list.add(1922);
            sqlSession.delete("goods.batchDelete", list);
            sqlSession.commit();
        }catch (Exception e){
            if(sqlSession!=null){
                sqlSession.rollback();
            }
            throw e;
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }
    }

posted @ 2022-04-20 23:42  南风知君  阅读(472)  评论(0)    收藏  举报