mybatis+oracle 批量操作

在mybatis中,对于oracle的批量操作有点特殊,用到了就记一下。

批量插入

  • 批量插入(带序列)
<insert id="batchInsert"  parameterType="java.util.List" useGeneratedKeys="false">
      INSERT TABLE(
      ID,
      FIELD1,
      FIELD2
      )
      SELECT ID.NEXTVAL,X.* FROM(
      <foreach collection="lsit" item="item" index="index" separator="union all">
        SELECT
        #{item.field1},
        #{item.field2}
        FROM DUAL
      </foreach>
      ) X
</insert>
  • 批量插入(不带序列)
<insert id="batchInsert"  parameterType="java.util.List" useGeneratedKeys="false">
    INSERT ALL
    <foreach collection="list" item="item" index="index">
      INTO TABLE
      (ID,FIELD1,FIELD2)
      values(#{item.id},#{item.field1},#{item.field2})
    </foreach>
    SELECT 1 FROM DUAL
</insert>

注:必须加 useGeneratedKeys="false" ,不信可以试试。。。
大概什么原因偶也不清楚,就是批量插入的时候不能返回主键吧。

批量更新

  <update id="batchUpdate" >
    <foreach collection="list" item="item" index="index" separator=";"  open="begin" close=";end;">
      UPDATE TABLE
      <set >
        <if test="item.field1!= null" >
          ADDING_OPENNESS = #{item.field1},
        </if>
        <if test="item.field2!= null" >
          NORMALLY_OPEN = #{item.field2},
        </if>
      </set>
      where ID= #{item.id}
    </foreach>
  </update>

批量删除

<delete id="batchDelete" parameterType="java.util.List">
DELETE FROM TABLE where ID in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item}
</foreach>
</delete>

批量查询

<select id="batchQuery" resultMap="BaseMap">
select ID,FIELD1,FIELD2
FROM TABLE
where ID in
<foreach collection="list" item="item" index="index" separator="," open="(" close=")">
#{item.id}
</foreach>
</select>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容