mybatis 支持批量update

有的時候我們需要將我們拼接的多條update語句放在mysql一個<update>標籤去執行,像平常那樣是不行的。

這就需要我們改一些東西了,首先我們需要在我們jdbcurl上拼接上allowMultiQueries=true,如下:

url="jdbc:mysql://localhost:8066/TESTDB?allowMultiQueries=true"

這個時候我們就可以在我們的<update>標籤中寫多個update語句了

如果update語句太多的話,比如有個上千條:我們可以在mysql 的my.cnf中配置如下:

wait_timeout=31536000
interactive_timeout=31536000

oracle數據庫: 
 

<update id="updatebatch"  parameterType="java.util.List">

  <foreach collection="list" item="item" index="index" open="begin" close="end;" separator=";">

update table_name 

    <set >

      <if test="item.status != null" >

        status = #{item.status,jdbcType=INTEGER},

      </if>

    </set>

    where id = #{item.id,jdbcType=BIGINT}

  </foreach>

    </update>

mysql數據庫: 

mysql數據庫採用一下寫法即可執行,但是數據庫連接必須配置:&allowMultiQueries=true 

例如:jdbc:mysql://192.168.1.232:3306/test?useUnicode=true&amp;characterEncoding=UTF-8&allowMultiQueries=true 

<update id="updatebatch"  parameterType="java.util.List">

  <foreach collection="list" item="item" index="index" open="" close="" separator=";">

update table_name 

    <set >

      <if test="item.status != null" >

        status = #{item.status,jdbcType=INTEGER},

      </if>

    </set>

    where id = #{item.id,jdbcType=BIGINT}

  </foreach>

       </update>

當然我們頁可以在代碼中動態拼接如下:

    public int batchUpdateTfrData(IRequest r, List<Long> aeTfrIdList, String mes, String accountStatus) {
        StringBuffer str = new StringBuffer();

        for(int i = 0; i < aeTfrIdList.size(); ++i) {
            str.append("update hsae_ae_tfr_events  set  ACCOUNTING_STATUS ");
            str.append(" = '" + accountStatus + "'");
            if (mes != null) {
                str.append(", ACCOUNTING_REMARKS");
                str.append(" = '" + mes + "'");
            }

            str.append(CommonUtils.whoUpdate(r));
            str.append(" where TFR_EVENT_ID =");
            str.append(aeTfrIdList.get(i));
                str.append(";");
        }
        this.aeEventBatchesMapper.updateSourceData(str.toString());

        return aeTfrIdList.size();
    }

xml:

    <update id="updateSourceData" parameterType="string">
        ${sqlText}
    </update>

 

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