您的位置:首页 > 其它

myBatis 批量操作

2013-12-25 13:07 411 查看
在批量操作数量级比较高时,尽量不要在service 层循环访问数据库,这会占用数据库的连接数

mybatis 中提供的批量操作函数 foreach ,通过生成批量处理sql 语句来实现批量操作

一 批量插入: (适用oracle)

<insert id="plInsert">
insert into plstu (id,name,sex)
<foreach collection="stus" item="stu" index="index" separator="union">
select #{stu.id},#{stu.name},#{stu.sex} from dual
</foreach>
</insert>

<!-- 批量删除 -->
<delete id="pldelete">
delete from plstu where name in
<foreach collection="stus" item="stu" index="index" separator="," open="(" close=")" >
#{stu.name}
</foreach>
</delete>
或者不要 open close 直接将foreach 标签() 起来

<!-- 批量更新 -->
<update id="plupdate">
<foreach collection="stus" item="stu" index="index" separator=";" open="begin" close=";end;" >
update plstu set name = #{stu.sex},sex = #{stu.name} where id = #{stu.id}
</foreach>
</update>

批量的本质。。。还是生成批量的sql处理语句交给数据库操作,只是减少了程序与数据库的互动次数

----------------------------oracle 批量操作--------------------------------------------------
1 批量插入

<insert id="saveEconomicByRows" parameterType="List">
insert into KJ_ECONOMIC_AWARD
(   id,
proid,
nd,
xzlr,
xzss,
cswh,
jzze)
select seq_kj_other_id.nextval,A.* from (
<foreach collection="list" item="row" index="index" separator="union">
select  #{row.proid,jdbcType=NUMERIC} as proid,
#{row.nd} as nd,
#{row.xzlr} as xzlr,
#{row.xzss} as xzss,
#{row.cswh} as cswh,
#{row.jzze} as jzze
from dual
</foreach>
)A
</insert>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: