ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • MyBatis 동적 SQL : if, choose(when, otherwise), trim, foreach
    Java/Spring 2022. 5. 31. 10:06

     


    MyBatis 
    Dynamic Sql : 검색 조건에 따라 검색해야하는 SQL문이 변경되어야하는 경우 사용한다.

    종류 : if, choose(when, otherwise), trim(where, set), foreach 


    if 


    형식 : <if test="컬럼명 조건"> </if>
    예시 : 

    <select id="findMovie" resultType="Movie">
        select * from MOVIE
        where rating > 8.5
        <if test="title != null">
            AND title like #{title}
        </if>
    </select>


    -> 파라미터로 title이 전달 되었다면 #{title} 이 포함된 평점 8.6 이상인 영화를 검색한다.

     

     




    choose, when, otherwise 


    형식 : <choose><when test="컬럼명 조건"> 실행문 </when> <otherwise> 실행문 </otherwise> </choose>
    예시 : 

    <select id="findMovie" resultType="Movie">
        select * from MOVIE where rating > 8.5
        <choose>
            <when test="title != null">
           	 	AND title like #{title}
            </when>
            <when test="director!=null and director.name !=null">
            	AND director_name like #{director}
            </when>
            <otherwise>
            	AND showing = 1;
            </otherwise>
        </choose>
    <select>



    -> 파라미터로 title 값이 전달되었다면 #{title}으로 영화 제목을 검색하고 director.name이 전달 되었다면 감독 이름으로 검색, 둘다 주어지지 않았다면 현재 상영중(showing = 1)인 평점이 8.6 이상 영화를 검색한다.
    if-else 문과 같은 연산이므로 title이 전달되었다면 이하의 when, otherwise문은 실행되지 않는다.

     




    trim, where, set 

    예를 들어 아래와 같은 sql문이 있다고 했을 때 

     

    <select id="findMovie" resultType="Movie">
        select * from MOVIE where 
        <if test="title != null">
    	    title like #{title}
        </if>
    	    <if test="director!=null and director.name !=null">
        AND director_name like #{director.name}
        </if>
    <select>

     

    전달된 파라미터 값이 하나도 없다면 select * from MOVIE where 이 되어 오류,
    director.name이 전달되어도 select * from MOVIE where AND director_name like #{director} 이 되므로 오류가 발생한다.

    이 때 사용할 수 있는 문법이 trim이다

    속성 

    • prefix="String" : 가장 앞에 지정한 문자열을 붙인다.
    • prefixOverrid="String" :  문 안의 쿼리 가장 앞에 있는 지정 문자열을 제거한다.
    • suffix="String" : 가장 뒤에 지정한 문자열을 붙인다.
    • suffixOverrides="String" : <trim>문 안의 쿼리 중 가장 뒤에 있는 지정 문자열을 제거한다.

     

    형식 : 속성 중 필요한 것만 적는다
    <trim prefix="String" prefixOverrides="String" suffix="String" suffixOverrides="String"><trim>

    예시 : 위에 잘못된 if문을 trim 문으로 바꿔 작성

    <select id="findMovie" resultType="Movie">
        select * from MOVIE
        <trim prefix="where" prefixOverrides="AND">
            <if test="title != null">
            	AND title like #{title}
            </if>
            <if test="director!=null and director.name !=null">
            	AND director_name like #{director.name}
            </if>
        </trim>
    <select>



    예시2 : update 문에서 trim문 사용하기

    <update id="updateMovie">
        update MOVIE 
        <trim prefix="SET" suffixOverrides=",">
            <if test="title != null"> title = #{title}, </if>
            <if test="director != null and director.name != null" > director_name = #{director.name}, </if>
            <if test="year != null"> year = #{year}, </if>
            <if test="showing != null"> showing = #{showing}, </if>
        </trim>
        where movie_no = #{movie_no}
    </update>

     




    foreach
    : 배열과 리스트를 사용하는 동적 sql, 주로 in구문과 함께 사용한다.

    속성 

    • collection : Array 혹은 List
    • item : collection에서 지정한 배열의 별칭
    • index : 반복되는 구문 번호
    • open : 구문이 시작될 때 삽입할 문자열 
    • close : 구문이 끝날 때 삽입할 문자열
    • separator : 반복문이 실행되는 사이에 출력할 문자열 

    형식 : </foreach collection="list 혹은 array" item="별칭" >


    예시 
    (movieList 는 보고싶어요에 담긴 영화 목록이라고 가정)

    <select id="findMovie" resultType="Movie">
        select * from Movie where title in 
        <foreach collection="list" index="index" item="list" open="(" separator="," close=")">
        	#{list}
        </foreach>
    </select>

     
    -> 배열이든 리스트든 그 자체를 직접 전달할 때는 collection에 Array 혹은 List 라고 쓰고 
    Map을 통해 전달할 때는 그 배열 혹은 리스트의 이름!(movieList)를 써줘야한다.

     

     

     

    참고한 문서와 블로그 

     

     

    https://mybatis.org/mybatis-3/dynamic-sql.html

     

    mybatis – MyBatis 3 | Dynamic SQL

    Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilities. If you have any experience with JDBC or any similar framework, you understand how painful it is to conditionally concatenate strings of SQL together, mak

    mybatis.org

     

    https://java119.tistory.com/85

     

    [MyBatis] 동적 쿼리 foreach문 문법 총 정리

    시작하기에 앞서 참고 자료 *ibatis iterate문 지원 태그 property : 파라미터명 prepend : 쿼리로 쓰일 문자 open : 구문이 시작될때 삽입할 문자열 close : 구문이 종료될때 삽입할 문자열 conjunction :..

    java119.tistory.com

     

    댓글

Designed by Tistory.