MyBatis ON DUPLICATE KEY UPDATE: insert Key 중복 시 update 처리

ON DUPLICATE KEY UPDATE: upsert 구현

`ON DUPLICATE KEY UPDATE``MySQL``MariaDB`에서 사용되는 SQL 문장 중 하나로, 주로 데이터를 삽입하려고 할 때 기존 레코드와 중복된 경우(중복 레코드) 기존 레코드를 업데이트하거나 무시하는데 사용됩니다.

 

중복 레코드:
데이터베이스에 이미 동일한 고유 키(primary key 또는 unique key)가 존재하는 경우, `ON DUPLICATE KEY UPDATE`를 사용하여 중복 레코드를 업데이트하거나 새로운 값을 가질 수 있습니다.

 

구문:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2, ...;

 

MyBatis에서의 구문:

  • <insert> 태그에서 upsert 구문을 작성할 수 있습니다.
  • INSERT 시 반환 값: 1
  • UPDATE 시 반환 값: 2
<insert id="upsertUser" parameterType="User">
    INSERT INTO user (user_id, user_password, user_name, phone, user_organization, subscription_service, create_date, update_date)
    VALUES (#{userId}, #{userPassword}, #{userName}, #{phone}, #{userOrganization}, #{subscriptionService}, NOW(), NOW())
    ON DUPLICATE KEY UPDATE
            user_name = #{userName},
        <if test="userPassword != null and userPassword != ''">
            user_password = #{userPassword},
        </if>
        <if test="userOrganization != null and userOrganization != ''">
            user_organization = #{userOrganization},
        </if>
        <if test="phone != null and phone != ''">
            phone = #{phone},
        </if>
        <![CDATA[ subscription_service = subscription_service | #{subscriptionService} ]]>,
        used_yn = 'Y',
        update_date = NOW()
</insert>