MySQL批量插入、批量更新及批量删除语句

摘要: 一、批量插入 <insert id="insertBatch" parameterType="java.util.List"> insert into t_student(name, age, class) ...java

一、批量插入sql

<insert 
        id="insertBatch" 
        parameterType="java.util.List">
        insert into 
            t_student(name, age, class)
        values
        <foreach collection="list"  item="item" index="index" separator=",">
            (
                #{item.name,jdbcType=VARCHAR}, 
                #{item.age,jdbcType=INTEGER},
                #{item.class,jdbcType=LONGVARCHAR}
            )
        </foreach>
   </insert>

二、批量更新数组

方式一:spa

<update id="updateBatch">
       <foreach collection="list" separator=";" item="stud">
            update t_studetn set
                name = #{stud.name},
                age = #{stud.age},
                class = #{stud.sex},
            where id = #{stud.id}
       </foreach>
</update>

方式二:code

<update id="updateBatch" parameterType="list">
  UPDATE t_student
  SET name = CASE id 
     <foreach collection="list" item="i" index="index">
        WHEN #{i.id} 
        THEN #{i.name}
     </foreach>
        END, 
        age = CASE id 
     <foreach collection="list" item="i" index="index">
        WHEN #{i.id} THEN #{i.age}
     </foreach>
        END
 WHERE id IN 
     <foreach collection="list" separator="or" item="i" index="index" >
        id=#{i.id}
     </foreach>
</update>

三、批量删除对象

<delete id="deleteBatchByParams">
        delete from 
            t_student
        where 
            id IN
        <foreach collection="ids" item="item" index="index" open="("close=")"separator=","> 
            #{item}
        </foreach>
</delete>

 

item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection

要作foreach的对象,做为入参时,List<?>对象默认用list代替做为键,数组对象有array代替做为键,Map对象没有默认的键。
固然在做为入参时能够使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种状况外,还有一种做为参数对象的某个字段的时候。举个例子:
若是User有属性List ids。入参是User对象,那么这个collection = "ids"
若是User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素作循环。
该参数为必选。
ci

separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号致使sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,通常是(和close=")"合用。经常使用在in(),values()时。该参数可选。
close foreach代码的关闭符号,通常是)和open="("合用。经常使用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。