Mybatis 批量增加/更新/刪除 操作,注意修改數據庫配置url !!

Mybatis 批量增刪改查CRUD操作

一個小坑,如果數據庫配置不加上allowMultiQueries=true這個屬性的話,執行時sql語句會報錯!

Srping:
  datasource:
    url: jdbc:mysql://localhost:3306/test?allowMultiQueries=true

結合動態sql 話不多說,直接上碼
// 批量插入

  <insert id="insert" parameterType="java.util.List" >
    insert into t_flow (id, group_id, flow_content,
      flow_time)
    values
    <foreach collection="list" item="item" index="index" separator=",">
      #{item.id,jdbcType=int},
      #{item.groupId,jdbcType=CHAR},
      #{item.flowContent,jdbcType=VARCHAR},
      #{item.flowTime,jdbcType=TIMESTAMP})
    </foreach>
  </insert>

//批量更新 (有則更新無則插入)

<insert id="insert" parameterType="java.util.List" >
    insert into t_flow (id, group_id, flow_content,
    flow_time)
    values
    <foreach collection="list" item="item" index="index" separator=",">
      (#{item.id,jdbcType=INTEGER},
      #{item.groupId,jdbcType=CHAR},
      #{item.flowContent,jdbcType=VARCHAR},
      #{item.flowTime,jdbcType=TIMESTAMP})
    </foreach>
    ON DUPLICATE KEY UPDATE
    group_id=VALUES(group_id),
    flow_content=VALUES(flow_content),
    flow_time=VALUES(flow_time)
  </insert>

//批量刪除

 <delete id="delete" parameterType="java.util.List">
        delete from t_flow where id in
        <foreach item="item" collection="list" open="(" separator="," close=")">
            #{item.id,jdbcType=INTEGER}
        </foreach>
    </delete>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章