当前位置: 首页 > news >正文

Mybatis批量操作

1、批量插入

 <!--批量操作-插入--><!-- 相当于INSERT INTO t_goods (c1,c2,c3) VALUES (a1,a2,a3),(b1,b2,b3),(d1,d2,d3),...--><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>

测试

 @Testpublic void batchInsertTest(){SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();PageHelper.startPage(1, 6);GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);List<Goods> goodsList = new ArrayList<Goods>();for (int i = 0; i < 10; i++) {Goods goods = new Goods();goods.setTitle("测试产品"+i);goods.setSubTitle("测试产品副标题"+i);goods.setDiscount(0.88f);goods.setIsFreeDelivery(1);goods.setOriginalCost(155f);goods.setCategoryId(40);goods.setCurrentPrice(888f);goodsList.add(goods);}int insert = mapper.batchInsert(goodsList);if (insert == goodsList.size()) {sqlSession.commit();System.out.println("插入数据成功");}else{System.out.println("插入数据失败");sqlSession.rollback();}} catch (Exception e) {System.out.println("插入数据失败");sqlSession.rollback();throw new RuntimeException(e);} finally {sqlSession.close();}}

1、批量插入数据无法获得插入数据的id,若后续需要使用该id继续操作,需要想别的办法
2、若批量插入的数据太多,生成的批量插入SQL过长,可能会被服务器拒绝,可以改为分成几次来完成

2、批量删除

<!--批量操作-删除-->
<!--相当于DELETE FROM t_goods WHERE goods_id IN (a1,a2,a3,a4,a5...)
-->
<delete id="batchDelete" parameterType="java.util.List">DELETE FROM t_goods WHERE goods_id IN<foreach collection="list" item="item" index="index" separator=","  open="(" close=")">#{item}</foreach>
</delete>

测试:

@Testpublic void batchDeleteTest(){SqlSession sqlSession = null;try {sqlSession=MyBatisUtil.getSqlSession();GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);List<Integer> parameterList = Arrays.asList(2600, 2601,2602);int delete = mapper.batchDelete(parameterList);if (delete == parameterList.size()) {System.out.println("删除数据成功");sqlSession.commit();}else{System.out.println("删除数据失败");sqlSession.rollback();}} catch (Exception e) {System.out.println("删除数据失败");sqlSession.rollback();throw new RuntimeException(e);} finally {sqlSession.close();}}

http://www.mrgr.cn/news/94602.html

相关文章:

  • 数据库的基本知识
  • LeetCode 热题 100_前 K 个高频元素(75_347_中等_C++)(堆)(哈希表+排序;哈希表+优先队列(小根堆))
  • @RequestParam、@RequestBody、@PathVariable
  • 虚幻基础:蓝图常用节点
  • 总结 HTTP 协议的基本格式, 相关知识以及抓包工具fiddler的使用
  • 【bug日记】 编译错误
  • 自由学习记录(44)
  • C++相关基础概念之入门讲解(上)
  • 用Lua脚本实现Redis原子操作
  • Qt 控件概述 QWdiget
  • Java数据结构第二十三期:Map与Set的高效应用之道(二)
  • A SURVEY ON POST-TRAINING OF LARGE LANGUAGE MODELS——大型语言模型的训练后优化综述——第2部分
  • 从0开始搭建微服务架构特别篇SpringCloud网关聚合knife4j
  • C语言【内存函数】详解加模拟实现
  • 【大模型基础_毛玉仁】2.4 基于 Encoder-Decoder 架构的大语言模型
  • Ansible 自动化运维
  • 路由器与防火墙配置命令
  • (done) 梳理 xv6-lab-2023 fs.img 生成过程,以及 xv6 磁盘结构
  • python速通小笔记-------1.容器
  • pytest 框架学习总结