• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
欢迎你来到 鸢羽 的博客!!
有交流才有进步, 记录我的学习笔记, 用我的经历, 让你少进一个坑, 让我们一起成长吧!
博客园    首页    新随笔    联系   管理    订阅  订阅
Mybatis里Mapper.xml加强

批量插入
insert into user(user_id,name) values (1,'test0'),(2,'test1');

<!-- 批量插入 -->
<insert id="batchInsert" parameterType="java.util.List">
insert into
user(
user_id,name
)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.userId},#{item.name})
</foreach>
</insert>

批量删除
delete from user where user_id in(1,2);
<!-- 批量删除 -->
<delete id="batchDel" parameterType="java.util.List">
delete from user
where
user_id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</delete>

批量更新
①:循环更新,连接数据库N次,效率低
update user set name = 'test0' where user_id=1;update user set name = 'test1' where user_id =2;

<!-- 批量更新 -->
<update id="batchUpdate" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update user
<set>
name=#{name}
</set>
where user_id = #{item.userId}
</foreach>
</update>

②:循环更新,连接数据库一次,效率较高(case when的两种写法)
写法一:
update user set name = case user_id when 1 then 'test0' when 2 then 'test1' else name end where user_id in(1,2)

<update id="batchUpdate" parameterType="java.util.List">
update user set name=
<foreach collection="list" item="item" index="index" separator=" " open="case user_id" close="end">
when #{item.userId} then #{item.name}
</foreach>
where user_id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.user_id}
</foreach>
</update>

写法二:
update user set name = case when user_id = 1 then 'test0' when user_id = 2 then 'test1' else name end where user_id in(1,2)

<update id="batchUpdate" parameterType="java.util.List">
update user
                 set name =
              <foreach collection="list" item="item" index="index" separator=" " open="case " close="else name end">
when user_id = #{item.userId} then #{item.name}
</foreach>
             where id in
                 <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
                 #{item.userId}
                 </foreach>
</update>

posted on 2019-05-21 18:01  鸢羽_颖  阅读(154)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3