MyBatis批量操作

前言:在项目中遇到了需要批量操作数据表的情况,笔者遇到的是更新操作。但在mybatis中批量操作有多种,因此在此对mybatis中的批量操作以及其注意点进行总结。


1.批量插入操作

批量插入,传入的是一个List对象的集合,因此在mapper文件中需要用循环的方式进行操作,具体格式如下:

<insert id="insertBatch" parameterType="java.utils.List">
       insert into tablename (xxx,xxx,xxx)
       values
        /*collection的属性值为接口中对应的参数名称
          (#{item.xxx},#{item.xxx},#{item.xxx}
           通过属性的方式取得对应的值,注意小括号的使用
        */
       <foreach collection="listxxx" item="item" separator=",">
           (#{item.xxx},#{item.xxx},#{item.xxx})
       </foreach>
 </insert>

mapper文件对应的接口形式如下:

public void insertBatch(@Param("listxxx") List<xxx> listxxx);

2.批量更新操作

批量更新操作,笔者总结了下面两种方式:

①使用循环update形式【这种方式需要特别注意,需要在数据库连接字符串中增加allowMultiQueries=true,不然会报异常】

 <update id="batchUpdate" parameterType="java.util.List">

        <foreach collection="list" index="index" item="item" separator=";">
            update t_demo_user set
            <if test="item.userName!=null">
               user_name=#{item.userName},
            </if>
            <if test="item.gender!=null">
                gender=#{item.gender}
            </if>
             where user_id=#{item.userId}
        </foreach>
 </update>

②使用 case 形式

 <update id="batchUpdate" parameterType="java.util.List">
        UPDATE  t_demo_user
        <trim prefix="set" suffixOverrides=",">
            <trim prefix="user_name= case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <if test="item.userName !=null">
                        when user_id=#{item.userId} then #{item.userName}
                    </if>
                </foreach>
            </trim>
            <trim prefix="gender= case" suffix="end,">
                <foreach collection="list" item="item" index="index">
                    <if test="item.gender !=null">
                        when user_id=#{item.userId} then #{item.gender}
                    </if>
                </foreach>
            </trim>
        </trim>
        where user_id in
        <foreach collection="list" item="item" index="index" separator="," open="(" close=")">
            #{item.userId}
        </foreach>
</update>

总结

通过以上方式可实现批量插入与批量更新,但是笔者并没有进行效率方面的测试,也可能直接批处理效率更高。


by Shawn Chen,2018.8.8日,下午。

原文地址:https://www.cnblogs.com/developer_chan/p/9320018.html