In this section, learn to use collections to save batch data, and then use batch sql (use foreach to traverse) to batch data at one time
One, batch add
- xml configuration
<!-- 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>
- test
@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);
}
}
Two, batch delete
- xml configuration
<!-- 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>
- test
@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);
}
}
Three, the limitations of batch inserting data
- Unable to get the id of the inserted data, if you want to do the subsequent processing through the id, it is not appropriate
- The sql generated in batch is too long and may be rejected by the server (solution: you can use segmentation, for example, if you want to import 100w data, you can complete the second nesting of for loop, import 1w at a time)