zoukankan      html  css  js  c++  java
  • myBatis 批量操作

    在批量操作数量级比较高时,尽量不要在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>

    1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list

    2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array

    3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map


  • 相关阅读:
    nodejs 访问mysql
    1.移动的矩形
    ubuntu 16.04 搜狗输入法无法中英文切换
    修改可选项文件实现自动连接数据库服务器
    Codeforces Round #374 (Div. 2)解题报告
    hihoCoder 1238 : Total Highway Distance(dfs + 二分)
    AIM Tech Round 3 (Div. 2) 题解
    Codeforces Round #367 (Div. 2) 题解
    图论模板集合
    poj1144Network (求割点模板题)
  • 原文地址:https://www.cnblogs.com/leonkobe/p/3490445.html
Copyright © 2011-2022 走看看