在批量操作数量级比较高时,尽量不要在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>
</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 标签() 起来
或者不要 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处理语句交给数据库操作,只是减少了程序与数据库的互动次数
批量的本质。。。还是生成批量的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>
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map