1.批量插入
<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
public void testBatchInsert(){
SqlSession session=null;
try{
long st=new Date().getTime();
session=MyBatisUtils.openSession();
List list=new ArrayList();
for (int i = 0; i < 10000; i++) {
Goods goods=new Goods();
goods.setTitle("测试商品");
goods.setSubTitle("测试子标题");
goods.setOriginalCost(200f);
goods.setCurrentPrice(100f);
goods.setDiscount(0.5f);
goods.setIsFreeDelivery(1);
goods.setCategoryId(43);
list.add(goods);
}
// insert()方法返回值代表本次成功插入的记录总数
session.insert("goods.batchInsert",list);
// 提交事务数据
session.commit();
long et=new Date().getTime();
System.out.println("执行时间:"+(et-st)+"毫秒");
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}
批量插入数据的局限性:
-
无法获取插入数据的id
-
批量生成的SQL太长,可能会被服务器拒绝文章来源:https://www.toymoban.com/news/detail-733252.html
2.批量删除
<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>
测试代码文章来源地址https://www.toymoban.com/news/detail-733252.html
/**
* 批量删除测试
*/
@Test
public void testBatchDelete(){
SqlSession session=null;
try{
long st=new Date().getTime();
session=MyBatisUtils.openSession();
List list=new ArrayList();
list.add(1910);
list.add(1911);
list.add(1912);
list.add(1913);
// delete()方法返回值代表本次成功删除的记录总数
session.delete("goods.batchDelete",list);
// 提交事务数据
session.commit();
long et=new Date().getTime();
System.out.println("执行时间:"+(et-st)+"毫秒");
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
}
到了这里,关于MyBatis批处理,使用foreach的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!