Study/Java

[MyBatis] 동적 쿼리 trim 사용방법

momong'-' 2021. 1. 4. 09:52

trim

동적 SQL을 사용하기 위해 사용되는 문법

보통 if문을 썼을 경우 함께 사용된다.


속성/문법

prefix: <trim>문 안의 쿼리 가장 앞에 붙여줌

<trim prefix="[문자열]">
	쿼리문
</trim>

prefixOverrides: <trim>문 안의 쿼리 가장 앞에 해당하는 문자들이 있으면 자동으로 지워줌

<trim prefixOverrides="[문자열]">
	쿼리문
</trim>

suffix: <trim>문 안의 쿼리 가장 뒤에 붙여줌

<trim suffix="[문자열]">
	쿼리문
</trim>

suffixOverrides: <trim>문 안의 쿼리 가장 뒤에 해당하는 문자들이 있으면 자동으로 지워줌

<trim suffixOverrides="[문자열]">
	쿼리문
</trim>

예제

prefix, prefixOverrides 사용

<select id="selectEmployees">
	SELECT
    	*
    FROM
    	EMPLOYEES
    <trim prifix="WHERE" prefixOverrides="AND | OR">
    	<if test="name != null">
        	AND NAME = #{name}
        </if>
        <if test="name != null">
        	OR DEPT = #{dept}
        </if>
        <if test="sal != null">
        	OR SAL = #{sal}
        </if>
    </trim>
</select>

suffix, sufiixOverrides 사용

<insert id="addEmployee">
	INSERT INTO EMPLOYEES
    <trim suffixOverrides="," suffix=")">
    (
    NAME,
    <if test="dept != null">
    DEPT,
    </if>
    <if test="email != null">
    EMAIL,
    </if>
    )
    VALUES
    (
    #{name},
    <if test="dept != null">
    #{dept},
    </if>
    <if test="email != null">
    #{email},
    </if>
    )
	</trim>
</insert>