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 ()”,执行会出错。

  • 相关阅读:
    CF 1292A 迷宫
    JSOI Salesman 树形Dp
    HDU-1051 一个DP问题
    洛谷 P2656 采蘑菇 树形DP+缩点+坑点
    JSOI 2016 病毒感染 辅助Dp问题
    Codeforces D. Color the Fence(贪心)
    Codeforces H. Maximal GCD(贪心)
    Codeforces J. A Simple Task(多棵线段树)
    Codeforces C. A Simple Task(状态压缩dp)
    子集生成的三种算法
  • 原文地址:https://www.cnblogs.com/hyzxx/p/5241604.html
Copyright © 2011-2022 走看看