Several ways to implement batch update in Mybatis

I. Overview

It is very simple to implement batch insertion in mybatis. Compared with everyone knows, I won’t go into details here. This article mainly describes how to implement batch update.

The following introduces the several methods to be discussed in this article, which are mainly implemented in xml, and do not include the methods that need to change the code logic . Here, in addition to the common cases mentioned on the Internet, there are also batch update methods suitable for mysql and oracle: 1. case when 2 .foreach into multiple SQL 3. ON DUPLICATE KEY UPDATE (mysql) 4. replace into (mysql)

This time, I will talk about these four methods.

2. case when

The batch update operation implemented in this way is very inefficient, and when there are many fields to be updated, the SQL statement will be particularly long.

<update id="updateBatch">
    update t_calendar_extend
    <trim prefix="set" suffixOverrides=",">
        <trim prefix="modify_time = case index" suffix="end,">
            <foreach collection="list" item="item">
                when #{item.index} then #{item.modifyTime}
            </foreach>
        </trim>
        <trim prefix="user_type = case index" suffix="end">
            <foreach collection="list" item="item">
                when #{item.index} then #{item.type}
            </foreach>
        </trim>
    </trim>
    <where>
        index in (
        <foreach collection="list" separator="," item="item">
            #{item.index}
        </foreach>
        )
    </where>
</update>

Here, the values ​​of modify_time and user_type are updated according to the index value. If there are several fields, it needs to be traversed several times, which is very inefficient.

Three, foreach into multiple sql

The simplest way is to use foreach to assemble multiple update statements, but the SQL statement in the Mybatis mapping file does not support the end of ";" by default, that is, it does not support the execution of multiple SQL statements. So you need to add &allowMultiQueries=true to the url connecting to mysql to execute it.

<update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update tableName
        <set>
            name=${item.name},
            name2=${item.name2}
        </set>
        where id = ${item.id}
    </foreach>      
</update>

四、ON DUPLICATE KEY UPDATE

ON DUPLICATE KEY UPDATE in MYSQL is based on the primary key (PRIMARY KEY) or unique index (UNIQUE INDEX).

Update if the unique identifier or primary key already exists, or insert as a new row if the unique identifier or primary key does not exist.

<update id="updateBatch">
    insert into t_output_calendar (index, 
      cal_date, user_type, create_time, 
      modify_time, delete_flag
      )
    values
    <foreach collection="list" item="item" index="index"
        separator=",">
        (
        #{item.index,jdbcType=INTEGER}, 
        #{item.calDate,jdbcType=TIMESTAMP}, 
        #{item.type,jdbcType=TINYINT}, 
        #{item.createTime,jdbcType=TIMESTAMP}, 
        #{item.modifyTime,jdbcType=TIMESTAMP}, 
        #{item.deleteFlag,jdbcType=TINYINT}
        )
    </foreach>
    ON DUPLICATE KEY UPDATE modify_time = VALUES(modify_time), user_type = VALUES(user_type);
</update>

Five, replace into

Msql's replace into is exactly the same as insert into, but it has an update function:

If it is found that this row of data already exists in the table (judged by the primary key or unique index), delete this row of data first, and then insert new data. Otherwise, insert new data directly.

Note that it deletes the data first, and then inserts it. This is ON DUPLICATE KEY UPDATEdifferent from that. If the current database user does not have delete permission, replace into cannot be used.

Example:

<insert id="updateBatch" parameterType="java.util.List">
    replace into t_output_calendar (index, cal_date, user_type, create_time, 
      modify_time, delete_flag
      )
    values
    <foreach collection="list" item="item" index="index"
        separator=",">
        (
        #{item.index,jdbcType=INTEGER}, 
        #{item.calDate,jdbcType=TIMESTAMP}, 
        #{item.type,jdbcType=TINYINT}, 
        #{item.createTime,jdbcType=TIMESTAMP}, 
        #{item.modifyTime,jdbcType=TIMESTAMP}, 
        #{item.deleteFlag,jdbcType=TINYINT}
        )
    </foreach>
</insert>

 

1. Insert into means to insert data, the database will check the primary key, and if there is a duplication, an error will be reported;

2. replace into means to insert and replace data. There is a PrimaryKey or unique index in the demand table. If the data already exists in the database, it will be replaced with new data. If there is no data effect, it will be the same as insert into;

-- 存在就更新:
REPLACE INTO 表名(字段1, 字段2, ...) VALUES(值1, 值2, ...), (值1, 值2, ...);

3. insert ignore means that if the same record already exists in the table, the current new data will be ignored;

-- 存在就忽略:
INSERT IGNORE 表名(字段1, 字段2, ...) VALUES(值1, 值2, ...), (值1, 值2, ...);

4. On duplicate key update This syntax can be used to determine whether the record exists when inserting the record. If it does not exist, insert it. Otherwise, it is very convenient to update, and there is no need to execute two SQL 

Guess you like

Origin blog.csdn.net/yyongsheng/article/details/127867105