oracle 批量插入数据

mapper.java文件

    public int addBatch(@Param("viewList") List<_java映射类> list);

xml文件

  <insert id="addBatch" parameterType="map" useGeneratedKeys="false">
        INSERT INTO _表名 
            (_字段名1,_字段名2,_字段名3,_字段名4,_字段名5,_字段名6)
        SELECT _字段名1,_字段名2,_字段名3,_字段名4,_字段名5,_字段名6 FROM (
        <foreach collection="viewList" item="item" index="index" separator="UNION">
            <if test="index == 0">
                SELECT
                #{item._java类映射_字段名1,jdbcType=VARCHAR} as _字段名1,
                #{item._java类映射_字段名2,jdbcType=VARCHAR} as _字段名2,
                #{item._java类映射_字段名3,jdbcType=VARCHAR} as _字段名3,
                #{item._java类映射_字段名4,jdbcType=VARCHAR} as _字段名4,
                #{item._java类映射_字段名5,jdbcType=VARCHAR} as _字段名5,
                #{item._java类映射_字段名6,jdbcType=VARCHAR} as _字段名6
                from dual where not exists (
                    select 1 from _表名 where _字段名1 = #{item._java类映射_字段名1} and _字段名2 = #{item._java类映射_字段名2}
                        and _字段名3 = #{item._java类映射_字段名3} and _字段名4 = #{item._java类映射_字段名4})
            </if>
            <if test="index!=0">
                SELECT
                 #{item._java类映射_字段名1,jdbcType=VARCHAR} ,
                #{item._java类映射_字段名2,jdbcType=VARCHAR} ,
                #{item._java类映射_字段名3,jdbcType=VARCHAR} ,
                #{item._java类映射_字段名4,jdbcType=VARCHAR} ,
                #{item._java类映射_字段名5,jdbcType=VARCHAR} ,
                #{item._java类映射_字段名6,jdbcType=VARCHAR} 
                from dual where not exists (
               select 1 from _表名 where _字段名1 = #{item._java类映射_字段名1} and _字段名2 = #{item._java类映射_字段名2}
                        and _字段名3 = #{item._java类映射_字段名3} and _字段名4 = #{item._java类映射_字段名4})
            </if>
        </foreach>
        )
    </insert>

插入数据去重:
<foreach collection="viewList" item="item" index="index" separator="UNION">
separator="UNION"
union去重并排序,union all直接返回合并的结果,不去重也不排序;


不过,上面这个union去重是指需插入的数据去重,且只能去重一模一样的数据
如何做到插入数据的时候,判断表里是否有包含指定的字段的数据是一致,其他字段不做判断,若指定的字段有一致的,则不插入数据, 需在插入数据的后面增加以下判断

where not exists (
   select 1 from _表名 where _字段名1 = #{item._java类映射_字段名1} 
   			and _字段名2 = #{item._java类映射_字段名2}
             and _字段名3 = #{item._java类映射_字段名3} 
             and _字段名4 = #{item._java类映射_字段名4}
             )
  1. union去重并排序,union all直接返回合并的结果,不去重也不排序;
  2. from dual 的Dual简单的说就是一个空表bai,Oracle提供的最小的工作表。
  3. <foreach >的具体用法:Mybatis——foreach用法
  4. not exists (sql 不返回结果集,为真);exists (sql 返回结果集,为真)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐