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

  • 相关阅读:
    AE的空间分析(转载)
    arcengine之版本管理
    执行 bower -v 时出现内部错误
    layui中获取全部提交的数据
    个推 简单的应用(安卓)
    在layui中,新的页面怎么获取另一个页面传过来的数据,并可以对数据进行判断,layui中的后台分页(table)。
    layui基本使用(动态获取数据,并把需要的数据传到新打开的窗口)
    layui的分页使用(前端分页)
    idea的热部署
    Lucene的步骤
  • 原文地址:https://www.cnblogs.com/hyzxx/p/5241604.html
Copyright © 2011-2022 走看看