存在即更新的关键字:ON DUPLICATE KEY UPDATE
向数据库表中插入一条记录:
- 若该数据行的主键值/UNIQUE KEY 已经在表中存在,则执行更新操作, 即UPDATE 后面的操作,否则插入一条新的记录。
单条数据存在即更新
<insert id="insertOrUpdate">
insert into t_employee_info
(code, name, six, age, description)
VALUES
(#{code,jdbcType=VARCHAR}
, #{name,jdbcType=VARCHAR}
, #{six,jdbcType=VARCHAR}
, #{age,jdbcType=INTEGER}
, #{description,jdbcType=VARCHAR})
ON DUPLICATE KEY UPDATE
code = values(code),
name = values(name),
six = values(six),
age = values(age),
description = values(description)
</insert>
批量数据存在即更新
<insert id="insertOrUpdateBatch">
insert into t_employee_info
(code, name, six, age, description)
VALUES
<foreach collection="list" index="index" item="item" separator=",">
(#{item.code,jdbcType=VARCHAR}
, #{item.name,jdbcType=VARCHAR}
, #{item.six,jdbcType=VARCHAR}
, #{item.age,jdbcType=INTEGER}
, #{item.description,jdbcType=VARCHAR})
</foreach>
ON DUPLICATE KEY UPDATE
code = values(code),
name = values(name),
six = values(six),
age = values(age),
description = values(description)
</insert>