专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 MyBatis批量的详细操作

MyBatis批量的详细操作

更新时间:2021-07-06 16:30:03 来源:赢咖4 浏览755次

在项目中遇到了需要批量操作数据表的情况,小编遇到的是更新操作。但在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.批量更新操作

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

(1)使用循环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>

(2)使用 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>

以上就是赢咖4小编介绍的"MyBatis批量的详细操作",希望对大家有帮助,想了解更多可查看Mybatis基础教程,如有疑问,请在线咨询,有专业老师随时为您服务。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>