본문 바로가기
Java/└ Mybatis

Mybatis) 동적쿼리 - 심화된 검색 기능 1-3 (where 태그)

by 박채니 2022. 8. 10.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


※ 흐름 - 이전 포스팅 참고

https://chanychu.tistory.com/366

 

Mybatis) 동적쿼리 - 심화된 검색 기능 1-2 (<![CDATA[]]>, <choose>분기처리)

안녕하세요, 코린이의 코딩 학습기 채니 입니다. 개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다. 검색타입, 성별, 급여에 대해 검색할 수 있도록 해보겠습니다. Controller EmpSe

chanychu.tistory.com

※ where 태그 없이 해결하는 방법 - 이전 포스팅

https://chanychu.tistory.com/365?category=991746 

 

Mybatis) 동적쿼리 - 심화된 검색 기능 1-1 (폼 초기화)

안녕하세요, 코린이의 코딩 학습기 채니 입니다. 개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다. 심화된 검색 기능 검색타입 (사번, 사원명, 이메일, 전화번호)과 성별을 이

chanychu.tistory.com

이전 포스팅까지는 반드시 true를 반환하는 1 = 1를 조건절에 써서 and를 해결했지만, where태그를 이용할 수도 있음!


<where> 태그

- 시작하는 and, or 제거

- where 태그 내부의 if문이 모두 false인 경우 (where 안이 빈 경우), where 키워드 제거

<select id="search2" resultMap="empMap">
    select
        e.*
    from (
        select
            e.*,
            decode(substr(emp_no, 8, 1), '1', '남', '3', '남', '여') gender
        from
            emp e
    ) e
    <where>
        <if test="searchType != null and searchType != '' and searchKeyword != null and searchKeyword != ''">
            ${searchType} like '%' || #{searchKeyword} || '%'
        </if>
        <if test="gender != null">
            and
            gender = #{gender}
        </if>
        <!-- 
        <if test="salary != null and salary != 0">
            <if test="salaryCompare != null and salaryCompare eq 'le'">
                and
                salary <![CDATA[ <= ]]> #{salary}
            </if>
            <if test="salaryCompare != null and salaryCompare eq 'ge'">
                <![CDATA[
                    and
                    salary >= #{salary}			
                ]]>
            </if>
        </if> 
        -->
        <!-- if, when의 test 속성에는
                && || < > <= >= 연산자 사용 불가
                and or lt gt le ge 사용할 것	
         -->
        <if test="salary != null and salary != 0">
            <choose>
                <when test="salaryCompare != null and salaryCompare eq 'le'">
                    and
                    salary <![CDATA[ <= ]]> #{salary}
                </when>
                <when test="salaryCompare != null and salaryCompare eq 'ge'">
                    <![CDATA[
                        and
                        salary >= #{salary}			
                    ]]>
                </when>
            </choose>
        </if>
    </where>
</select>