Mybatis批量更新三种方式的实现
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)

Mybatis批量更新三种方式的实现 Mybatis是一款流行的持久层框架,它提供了强大的数据库交互能力。其中,批量更新是一种常见的操作,能够提高数据库操作的效率。下面将介绍Mybatis批量更新三种方式的实现。 方式一:使用foreach标签 在Mybatis映射文件中,我们可以使用foreach标签来实现批量更新。例如: ``` <update id="updateBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update tableName <set> name=${item.name}, name2=${item.name2} </set> where id = ${item.id} </foreach> </update> ``` 这种方式可以实现批量更新,但是需要注意的是,Mybatis映射文件中的sql语句默认是不支持以`;`结尾的,也就是不支持多条sql语句的执行。所以需要在连接mysql的url上加`&allowMultiQueries=true`,这样才能执行多条sql语句。 方式二:使用trim和foreach标签 第二种方式是使用trim和foreach标签来实现批量更新。例如: ``` <update id="updateBatch" parameterType="java.util.List"> update tableName <trim prefix="set" suffixOverrides=","> <trim prefix="c_name =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.name!=null"> when id=#{cus.id} then #{cus.name} </if> </foreach> </trim> <trim prefix="c_age =case" suffix="end,"> <foreach collection="list" item="cus"> <if test="cus.age!=null"> when id=#{cus.id} then #{cus.age} </if> </foreach> </trim> </trim> <where> <foreach collection="list" separator="or" item="cus"> id = #{cus.id} </foreach> </where> </update> ``` 这种方式貌似效率不高,但是可以实现,而且不用改动mysql连接。 方式三:使用SqlSessionFactory和SqlSession 第三种方式是使用SqlSessionFactory和SqlSession来实现批量更新。例如: ``` public int updateBatch(List<Object> list){ if(list ==null || list.size() <= 0){ return -1; } SqlSessionFactory sqlSessionFactory = SpringContextUtil.getBean("sqlSessionFactory"); SqlSession sqlSession = null; try { sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false); Mapper mapper = sqlSession.getMapper(Mapper.class); int batchCount = 1000;//提交数量,到达这个数量就提交 for (int index = 0; index < list.size(); index++) { Object obj = list.get(index); mapper.updateInfo(obj); if(index != 0 && index%batchCount == 0){ sqlSession.commit(); } } ... } ``` 这种方式可以实现批量更新,但是无法返回受影响数量。 Mybatis批量更新三种方式的实现都有其优缺点,选择哪种方式取决于具体的业务场景和需求。





















- 粉丝: 10
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 嵌入式系统复习题1.doc
- 沁阳市第一中学多媒体设备及计算机设备采购项目.doc
- 肯德基网络营销策划分析ppt课件.ppt
- 有答案的《工程项目管理》复习题.doc
- 石油总公司中下游工程建设项目管理规定教材.doc
- 某自动化股份公司IEC61850技术培训.pptx
- 云计算建设方案样本.doc
- 工程网络计划网络图.ppt
- 数学建模网络赛特等奖土地储备风险评估方案.doc
- 网络故障分析报告.pdf
- 李宁电子商务方案解读.ppt
- 网络时间协议简介.doc
- (源码)基于C++的Vive Lighthouse室内定位传感器系统.zip
- 两个开挂的Excel同步数据到Word技巧!(联动)get√.pdf
- 智慧城市建设带动实体经济发展.docx
- 三级网络第一章的重点(最新整理).pdf



评论1