# 批处理

### 批处理使用场景

假设需要一次性插入1000条数据到数据表中，那么一条条书写 SQL 肯定不现实。这时候如果有一个list, 将所有待更新数据放在里面，传入一个list, 一次性更新则是最好的。

### 修改 goods.xml

在 MyBatis\src\main\resources\mappers\goods.xml 中添加下列标签

```xml
    <!-- INSERT INTO table
        VALUES ("a1","a2","a3"), ("b1","b2","b3"), (...) -->
    <select 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>
    </selectx
```

### 修改 MyBatisTest.java&#x20;

在MyBatis\src\test\java\MyBatisTest.java 内添加下列方法:

```java
    @Test
    public void testBatchInsert () throws Exception{
        SqlSession sqlSession=null;
        try {
            sqlSession=MyBatisUtils.openSession();
            List list=new ArrayList();
            for (int i = 0; i < 2; i++) {
                Goods g= new Goods();
                g.setTitle("批处理测试商品");
                g.setSubTitle("批处理测试子标题");
                g.setOriginalCost(100f);
                g.setCurrentPrice(50f);
                g.setDiscount(0.5f);
                g.setIsFreeDelivery(1);
                g.setCategoryId(43);
                list.add(g);
            }
            sqlSession.insert("goods.batchInsert", list);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }finally {
            MyBatisUtils.closeSession(sqlSession);
        }

    }
```

运行结果：

```
10:08:43:707 [main]  DEBUG goods.batchInsert -==>  Preparing: INSERT INTO t_goods(title, sub_title, original_cost, current_price, discount, is_free_delivery,category_id) VALUES (?, ?, ?, ?, ?,?,?) , (?, ?, ?, ?, ?,?,?)  
10:08:43:741 [main]  DEBUG goods.batchInsert -==> Parameters: 批处理测试商品(String), 批处理测试子标题(String), 100.0(Float), 50.0(Float), 0.5(Float), 1(Integer), 43(Integer), 批处理测试商品(String), 批处理测试子标题(String), 100.0(Float), 50.0(Float), 0.5(Float), 1(Integer), 43(Integer) 
10:08:43:744 [main]  DEBUG goods.batchInsert -<==    Updates: 2 
```
