반응형

오늘은 MyBatis에서 UPDATE 문을 효과적으로 처리할 수 있도록 돕는 <set> 태그를 학습합니다. 이 태그는 UPDATE 문에서 동적 필드 변경을 깔끔하게 관리하는 데 유용합니다.


1. <set> 태그란?

  • UPDATE 문에서 동적 필드를 추가하거나 변경할 때 사용됩니다.
  • 불필요한 쉼표(,)를 자동으로 제거하여 SQL 문 오류를 방지합니다.
  • 특정 조건에 따라 필드를 업데이트해야 하는 경우 적합합니다.

2. 실습: <set> 태그 사용하기

(1) 매퍼 파일 작성

아래는 직원 정보를 업데이트하는 SQL 예제입니다.

<mapper namespace="com.example.mapper.EmployeeMapper">

    <update id="updateEmployee" parameterType="map">
        UPDATE employees
        <set>
            <if test="firstName != null">
                first_name = #{firstName},
            </if>
            <if test="lastName != null">
                last_name = #{lastName},
            </if>
            <if test="email != null">
                email = #{email},
            </if>
            <if test="phoneNumber != null">
                phone_number = #{phoneNumber},
            </if>
        </set>
        WHERE employee_id = #{employeeId}
    </update>

</mapper>

설명:

  • <set> 태그는 조건문에 따라 필드 업데이트를 동적으로 처리합니다.
  • 필드 사이에 자동으로 쉼표를 추가하지만, 마지막 쉼표는 제거됩니다.
  • WHERE 조건을 명시하여 특정 레코드만 업데이트합니다.

(2) Mapper 인터페이스 작성

package com.example.mapper;

import org.apache.ibatis.annotations.Param;

public interface EmployeeMapper {
    int updateEmployee(@Param("employeeId") int employeeId,
                       @Param("firstName") String firstName,
                       @Param("lastName") String lastName,
                       @Param("email") String email,
                       @Param("phoneNumber") String phoneNumber);
}

(3) 테스트 코드 작성

package com.example;

import com.example.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TestRunner implements CommandLineRunner {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void run(String... args) throws Exception {
        int employeeId = 100; // 업데이트할 직원 ID
        String firstName = "John"; // 업데이트할 이름
        String lastName = "Doe";
        String email = "john.doe@example.com";
        String phoneNumber = null; // 업데이트하지 않을 필드는 null로 설정

        int rowsAffected = employeeMapper.updateEmployee(employeeId, firstName, lastName, email, phoneNumber);

        if (rowsAffected > 0) {
            System.out.println("직원 정보가 성공적으로 업데이트되었습니다.");
        } else {
            System.out.println("업데이트에 실패했습니다.");
        }
    }
}

3. 동작 원리

  • firstName, lastName, email, phoneNumber 값이 null일 경우 해당 필드는 업데이트 대상에서 제외됩니다.
  • WHERE employee_id = #{employeeId} 조건에 따라 특정 직원의 정보만 업데이트합니다.

4. <set> 태그의 장점

  1. 코드 가독성: 조건에 따라 업데이트할 필드를 쉽게 추가할 수 있습니다.
  2. SQL 오류 방지: 동적으로 SQL을 생성하면서 마지막 쉼표를 제거합니다.
  3. 유지보수 용이성: 필드 변경이나 추가 시 코드를 간단히 수정할 수 있습니다.

5. 오늘의 요약

  • <set> 태그는 UPDATE 문을 작성할 때 필드와 조건에 따라 동적 SQL을 깔끔하게 구성합니다.
  • 동적 SQL로 불필요한 쉼표를 자동으로 제거하여 오류를 방지합니다.
  • 이를 활용하면 효율적인 데이터 업데이트 처리가 가능합니다.
반응형

+ Recent posts