最近在使用mybaits的过程中经常会碰到批量插入、更新的需求,经过查询资料和调试,现在总结如下(数据库mysql、oracle)
一、批量更新
1、oracle数据库
<update >
<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 >
<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 >
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 >
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 >
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 ()”,执行会出错。