zoukankan      html  css  js  c++  java
  • mybatis批量foreach的使用

      最近在使用mybaits的过程中经常会碰到批量插入、更新的需求,经过查询资料和调试,现在总结如下(数据库mysql、oracle)

      一、批量更新

        1、oracle数据库

    <update id="batchUpdate" parameterType="list">
    	<foreach collection="list" item="item" index="index" separator=";" open="begin" close=";end;" >
    		update t_repay_plan a set 
    			a.repay_day = #{item.repayDay},
    			modify_date = sysdate,
    			modifier = #{currUser}
    		where a.lr_id = #{item.lrId} 
    	</foreach>
    </update>
    

        2、mysql数据库

         mysql数据库需要注意一点,数据库连接必须配置:&allowMultiQueries=true

         例如:jdbc:mysql://localhost/test?characterEncoding=UTF8&allowMultiQueries=true

          

    <update id="bantchUpdate" parameterType="list">
            <foreach collection="list" item="item" index="index" separator=";" open="" close=";">
                update t_repay_plan a set 
                       a.repay_day = #{item.repayDay},
                       modify_date = sysdate,
                       modifier = #{currUser}
                     where a.lr_id = #{item.lrId}
            </foreach>
        </update>

      二、批量插入

      1、oracle数据库

    <select id="insertRepayPlan" parameterType="list" >
            insert into t_repay_plan (RP_ID,LR_ID,ORDER_PERIODS)
            <foreach collection="list" item="item" index="index" separator="union all">
                (select
                    #{item.rpId},
                    #{item.lrId},
                    #{item.orderPeriods}
                from dual)
            </foreach>                 
    </select>

       2、mysql数据库

    <insert id="bantchInsertIntoUser" parameterType="list">
            INSERT into `user` (user_name,user_age,user_address) VALUES 
            <foreach collection="list" item="item" index="index" separator="," open="" close="">
                (#{item.user_name},#{item.user_age},#{item.user_address})
            </foreach>
        </insert>

       三、查询的时候用于

        1、mysql数据库

    <select id="selectUsersById"  resultType="user">
            select * from `user` 
            <if test="list!=null and list.size()!=0">
                where id in
                <foreach collection="list" item="id" index="index" separator="," open="(" close=")">
                    #{id}
                </foreach>
            </if>
        </select>

    动态的sql支持list.size()这种写法,如果不加<if>的判断,当传入的list为空时,动态的sql语句为“select * from `user`   where id in ()”,执行会出错。

  • 相关阅读:
    hive:Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
    spark报错:Class org.apache.mapreduce.io.compress.GzipCodec not found
    flink操作mysql
    kettle解除同步条数限制
    hdfs上传文件报错,org.apache.hadoop.fs.ChecksumException:
    spark程序运行报错:java.lang.NoSuchMethodError:
    git merge的三种操作merge, squash merge, 和rebase merge
    高人制作的CocosCreator分包插件
    Android Studio 编译构建报错总结
    Mac OSX下修改 ulimit 参数
  • 原文地址:https://www.cnblogs.com/hyzxx/p/5241604.html
Copyright © 2011-2022 走看看