MySQL insertOrUpdate 存在时更新,不存在时插入

版权声明:本博客为学习、笔记之用,以笔记形式记录学习的知识与感悟。学习过程中可能参考各种资料,如觉文中表述过分引用,请务必告知,以便迅速处理。如有错漏,不吝赐教。 https://blog.csdn.net/Cappadocia_/article/details/83383256

前提:判断更新或者插入的条件是 表里的唯一索引是否冲突,比如插入主键值相同的数据。

如需要根据某个键值来判断,必须创建唯一索引。

方式:使用 ON DUPLICATE KEY UPDATE 命令

Mybatis

<insert id="insertOrUpdate" parameterType="java.util.List" useGeneratedKeys="true"
            keyProperty="id">
        insert into user_agree_protocol(
        id,
        user_id,
        protocol_id,
        protocol_version
        )
        values
        <foreach collection="list" item="item" index="index"
                 separator=",">
        ( #{item.id},
          #{item.userId},
          #{item.protocolId},
          #{item.protocolVersion})
        </foreach>
        ON DUPLICATE KEY UPDATE
            protocol_version = VALUES (protocol_version)
</insert>

SQL语句的写法和MyBatis写法差不多,就不单独给出了。这里用VALUES就可以直接拿到原本要插入但插入失败的值。

猜你喜欢

转载自blog.csdn.net/Cappadocia_/article/details/83383256