❓ 동적 SQL(SQL의 재사용성과 유연성을 향상하고자 Dynamic SQL을 지원한다)
하나의 SQL문을 다양한 형태로 실행하는 기능이 동적SQL이다. MyBatis는 if, choose(when, otherwise), trim(where, set), foreach 요소의 동적 SQL을 지원한다.
if
<if> 요소는 test의 조건문이 참일 때 연결문자열을 SQL문에 연결하고, 그렇지 않으면 무시한다. 동적 SQL에서 가장 공통적으로 사용되며, SQL문에서 where절의 포함 여부를 작성할 수 있다.
<if test="조건문"> 연결문자열 </if>
choose, when, otherwise
choose~when~otherwise는 if와 함께 가장 공통적으로 제공되는 분기 처리 방식이다.
choose 하위의 when 엘리먼트에서 만족하는 조건이 하나라도 나오면 해당 조건의 결과를 동적 SQL에 적용하고 하나라도 없으면 otherwise 엘리먼트의 결과를 동적 SQL에 사용한다.
<choose>
<when test="조건문1">연결문자열1</when>
...
<when test="조건문n">연결문자열n</when>
<otherwise>연결문자열</otherwise>
</choose>
trim, where, set
if, choosw 등을 사용하여 조건의 결과가 참이 되지 않을 경우 완전하지 못한 SQL문의 요소를 제거하는 trim, where, set이 있다.
<trim>은 제거할 요소를 기술한다.
--WHERE절에 기술한 AND나 OR의 연산자를 제거한다.
<trim prefix="WHERE" prefixOverrides="AND|OR"> ... </trim>
1. prefix : 처리 후 엘리먼트의 내용이 있으면 가장 앞에 붙여준다.
2. prefixOverrides : 처리 후 엘리먼트 내용 중 가장 앞에 해당 문자들이 있다면 자동으로 지워준다.
3. suffix : 처리 후 엘리먼트 내에 내용이 있으면 가장 뒤에 붙여준다.
4. suffixOverrides : 처리 후 엘리먼트 내용 중 가장 뒤에 해당 문자들이 있다면 자동으로 지워준다.
--<trim>요소로 제거할 prefix와 suffixOverrides를 기술한다.
<update id="updateDepartment" parameterType="DeptVO">
update department
<trim prefix="SET" suffixOverrides=",">
<if test="dept_name!=null">dept_name=#{dept_name},</if>
<if test="dept_tel!=null">dept_tel=#{dept_tel}</if>
</trim>
where dept_id=#{dept_id}
</update>
<where>은 SQL문 내에 기술한 <where> ~ </where>내의 조건이 모두 참이 되지 않을 경우 <where> ~ </where>의 모든 문자열을 제거한다.
<where>
<if test="조건문1">연결문자열1</if>
...
<if test="조건문n">연결문자열n</if>
</where>
동적인 SELECT문은 <if>의 조건에 따라 조건이 모두 null이라면 where만 남게 되어 오류가 발생할 수 있다.
--오류가 발생할 수도 있는 동적인 SELECT문
<select id="selectFind" resultType="StudentVO">
select * from student
where
<if test="dept_name!=null">dept_name=#{dept_name}</if>
<if test="s_sex!=null">s_sex=#{s_sex}</if>
<if test="s_year!=null">s_year=#{s_year}</if>
</select>
=> 이럴 때는 <where> ~ </where>내에 기술하면 문제를 해결할 수 있다. <where>의 조건이 참이 되면 "WHERE"을 추가하고, 그렇지 않으면 제거한다.
<select id="selectFind" resultType="StudentVO">
select * from student
<where>
<if test="dept_name!=null">dept_name=#{dept_name}</if>
<if test="s_sex!=null">s_sex=#{s_sex}</if>
<if test="s_year!=null">s_year=#{s_year}</if>
</where>
</select>
<set>은 동적인 UPDATE문의 <if>문이 모두 참이 되지 않을 경우 <set>~</set> 문자열을 제거한다.
<set>
<if test="조건문1">연결문자열1</if>
...
<if test="조건문n">연결문자열n</if>
</set>
<set>은 동적인 update문에서 <if>의 조건이 참이 될 때 set을 추가하고 불필요한 컴마(,)를 제거한다.
<update id="updateDepartment" parameterType="DeptVO">
update department
<set>
<if test="dept_name != null">dept_name=#{dept_name},</if>
<if test="dept_tel != null">dept_tel=#{dept_tel}</if>
</set>
where dept_id=#{dept_id}
</update>
'MyBatis' 카테고리의 다른 글
CDATA Section (0) | 2023.10.07 |
---|---|
ResultMap (0) | 2023.10.07 |
바인딩변수를 이용한 SQL문 (0) | 2023.10.06 |
MyBatis 프레임워크 (3) | 2023.10.06 |
mybatis-config.xml 설정파일 (0) | 2023.08.07 |