mybatis中批量更新多个字段的2种实现方法
在mybatis中批量更新多个字段
推荐使用如下操作:
方式1:在Dao层接口中:
void updateBatch(@Param("list")List<Student> list);
在对应的mapper文件中如下:
<update id="updateBatch" parameType="java.lang.List"> update student <trim prefix="set" suffixOverrides=","> <trim prefix=" age = case " suffix="end,"> <foreach collection="list" item="stu" index="index"> <if test=" item.age != null and item.id != null"> when id = #{item.id} then #{item.age} </if> <if test=" item.age == null and item.id != null"> when id = #{item.id} then mydata_table.age //原始值 </if> </foreach> </trim> <trim prefix=" name = case" suffix="end,"> <foreach collection="list" item="stu" index="index"> <if test=" item.name!= null and item.id != null"> when id = #{item.id} then #{item.name} </if> <if test=" item.name == null and item.id != null"> when id = #{item.id} then mydata_table.name //原始值 </if> </foreach> </trim> </trim> </update>
上面的sql语句打印出来,应该是这个样子的:
update student set age = case when id = #{item.id} then #{item.status}//此处应该是<foreach>展开值 when id = #{item.id} then #{item.status} .... end, name = case when id = #{item.id} then #{item.status} ... end where id in (?,?,?,?...);
<trim>属性说明
1.prefix,suffix 表示在trim标签包裹的部分的前面或者后面添加内容
2.如果同时有prefixOverrides,suffixOverrides 表示会用prefix,suffix覆盖Overrides中的内容。
3.如果只有prefixOverrides,suffixOverrides 表示删除开头的或结尾的xxxOverides指定的内容
方式2:在Dao层接口方法定义同上
mapper文件如下:
<update id="updateBatch" parameterType="java.util.List"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> update student <set> name=#{item.name}, age = #{item.age} </set> where id = #{item.id} </foreach> </update>
到此这篇关于mybatis中批量更新多个字段的2种实现方法的文章就介绍到这了,更多相关mybatis 批量更新多个字段内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot pdf打印及预览(openhtmltopdf+freemarker)
这篇文章主要介绍了SpringBoot pdf打印及预览(openhtmltopdf+freemarker)2023-05-05Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验
这篇文章主要介绍了Springboot 使用 JSR 303 对 Controller 控制层校验及 Service 服务层 AOP 校验 使用消息资源文件对消息国际化的相关知识,需要的朋友可以参考下2017-12-12Idea 2020.2安装MyBatis Log Plugin 不可用的解决方法
小编在使用时发现Idea 2020.2 MyBatis Log Plugin 收费了,这个可以替代用,小编特此把解决方案分享到脚本之家平台供大家参考,感兴趣的朋友一起看看吧2020-11-11
最新评论