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

  • 相关阅读:
    GridView中实现点击某行的任意位置就选中该行
    HtmlEncode、HtmlDecode、UrlEncode、UrlDecode
    Asp.net中从后台中如何获取html控件
    关于IE10出现LinkButton点击无效的解决方案
    【转】关于IE7 z-index问题完美解决方案
    【转】Asp.net中时间格式化的6种方法详细总结
    【转】asp.net Cookie值中文乱码问题解决方法
    asp.net中Cookie的用法【转】
    【转】ASP.NET Cookies简单应用 记住用户名和密码
    ASP.NET Cookie 概述【转】
  • 原文地址:https://www.cnblogs.com/hyzxx/p/5241604.html
Copyright © 2020-2023  润新知