zoukankan      html  css  js  c++  java
  • mybatis批量插入和批量更新

    批量插入数据使用的sql语句是:

    insert into table (aa,bb,cc) values(xx,xx,xx),(oo,oo,oo)

    mybatis中mapper.xml的代码如下:

      <!-- 批量插入数据 -->
        <insert id="insertBatch" parameterType="java.util.List"
            useGeneratedKeys="true">
            <selectKey resultType="long" keyProperty="id" order="AFTER">
                SELECT
                LAST_INSERT_ID()
            </selectKey>
            insert into wd_solr
            (fayu_id, tablename,
            name,logo,description,section_no,look_count,favorite_count,create_uid,create_time,update_time,timestamp)
            values
            <foreach collection="list" item="wdSolr" index="index"
                separator=",">
                (
                #{wdSolr.fayuId},#{wdSolr.tablename},#{wdSolr.name},#{wdSolr.logo},
                #{wdSolr.description},#{wdSolr.sectionNo},#{wdSolr.lookCount},#{wdSolr.favoriteCount},
                #{wdSolr.createUid},#{wdSolr.createTime},#{wdSolr.updateTime},#{wdSolr.timestamp}
                )
            </foreach>
        </insert>

    批量更新数据使用的sql语句是:

    UPDATE table
        SET aa = CASE id
            WHEN 1 THEN 'oo'
            WHEN 2 THEN 'pp'
            WHEN 3 THEN 'qq'
        END
      ,SET bb = CASE id
            WHEN 1 THEN 'xx'
            WHEN 2 THEN 'yy'
            WHEN 3 THEN 'zz'
        END
    WHERE id IN (1,2,3)

    上面这一条mysql语句可以更新多条记录,mybatis中mapper.xml的代码如下:

      <!-- 批量更新数据 -->
        <update id="updateBatch">
            update wd_solr set
            name =
            <foreach collection="list" item="wdSolr" index="index"
                separator=" " open="case id" close="end">
                when #{wdSolr.id} then
                #{wdSolr.name}
            </foreach>
            ,logo =
            <foreach collection="list" item="wdSolr" index="index"
                separator=" " open="case id" close="end">
                when #{wdSolr.id} then
                #{wdSolr.logo}
            </foreach>        
            ,timestamp =
            <foreach collection="list" item="wdSolr" index="index"
                separator=" " open="case id" close="end">
                when #{wdSolr.id} then #{wdSolr.timestamp}
            </foreach>
            where id in
            <foreach collection="list" item="wdSolr" index="index" 
                separator="," open="(" close=")">
                #{wdSolr.id}
            </foreach>
        </update>
  • 相关阅读:
    《图解算法》读书笔记(十)K最近邻算法
    《图解算法》读书笔记(九) 动态规划
    《图解算法》读书笔记(八) 贪婪算法
    Go 常用包之fmt、flag包(四)
    GO环境及初始化项目(二)
    nginx fpm 常见错误对比分析
    Ueditor富文本添加、编辑视频,视频不显示解决方案
    phpunit 测试
    mysql 主从并行复制(MTS)
    Explain执行计划详解
  • 原文地址:https://www.cnblogs.com/Jason-Xiang/p/6558334.html
Copyright © 2011-2022 走看看