레이블이 mybatis인 게시물을 표시합니다. 모든 게시물 표시
레이블이 mybatis인 게시물을 표시합니다. 모든 게시물 표시

MyBatis 동적 쿼리 - choose

*** choose 문 ***
스위치 구문과 비슷. 여러 조건을 순서대로 체크하여 해당하는 조건의 구문을 추가.
해당되는 조건이 없을 경우 otherwise에 해당하는 구문을 추가

ex)
<select id="testSql" parameterType="hashmap" resultType="hashmap">
    select
        ID, NAME
    from
        T_TEST A
    where USE_YN = 'Y'
    <choose>       
        <when test="type == 'A' ">
            and TYPE = 'A'
        </when>       
        <when test="type == 'B' ">
            and TYPE = 'B'
        </when>
        <otherwise>
            and TYPE = 'C'
        </otherwise>
    </choose>
</select>

interface 형식
@Select("<script>"
    + "select "
    + " ID, NAME "
    + "from T_TEST A "
    + "where USE_YN = 'Y' "
    + " <choose>"
    + "   <when test=\"type == 'A'\"> TYPE = 'A' </when>"
    + "   <when test=\"type == 'B'\"> TYPE = 'B' </when>"
    + "   <otherwise> TYPE = 'C' </otherwise>"
    + " </choose>"
    + "</script> ")
List<HashMap> select(@Param("type")String type);

MyBatis 동적 쿼리 - if

*** if 문 ***
조건을 만족하는 경우 추가

ex) type 값이 null이 아니고, 빈값이 아닐때 조건에 추가
xml 형식
<select id="testSql" parameterType="hashmap" resultType="hashmap">
    select
        ID, NAME
    from
        T_TEST A
    where USE_YN = 'Y'
    <if test="type != null and type != ''"> and TYPE = #{type} </if>
</select>

interface 형식
@Select("<script>"
    + "select "
    + " ID, NAME "
    + "from T_TEST A "
    + "where USE_YN = 'Y' "
    + "<if test=\"type != null and type != ''\"> and TYPE = #{type} </if>"
    + "</script> ")
List<HashMap> select(@Param("type")String type);

MyBatis 동적 쿼리 - if, choose

*** if ***
일반 IF 문과 비슷.
값이 빈 값이 아닐때 조회 조건에 추가하는 경우 사용.

ex)
<select id="sel" resultType="HashMap"> 
   select * from T_TEST T
   where T.ID = 'id'
   <if test="name != null and name != ''">
      and T.NAME = #{name}
   </if>
</select>
 
*** choose ***
자바에서 사용하는 switch 문과 비슷.
choose 태그 내에서 when , otherwise 태그 사용.
when 조건과 일치하면 해당 쿼리문을, 일치하는 것이 없으면 otherwise 태그의 쿼리문을 추가
ex)
<select id="sel" resultType="HashMap">
   select * from T_TEST T 
   where T.ID = 'id'
   <choose>
      <when test="period > 20">
          and T.PERIOD > #{period}
      </when>

      <when test="period < 20">
          and T.PERIOD < #{period}
      </when>
      <otherwise>
          and T.PERIOD = 20
      </otherwise>
   </choose>

</select>

MyBatis (iBatis) 특수문자 처리

쿼리에 특수문자가 있는 경우 에러가 발생하는데

<![CDATA[ ]]> 태그를 사용하면 정상적으로 실행된다.

***사용예(XML) ***
<select id="getMoney"  parameterType="map" resultMap="HashMap">
    SELECT *
        FROM USER
    WHERE MONEY <![CDATA[ < ]]> 10000
</select>

***사용예(java class) ***
@Insert(""
            + "<script><![CDATA["
            + "    INSERT INTO USER (USER_ID, USER_NM, MONEY)"
            + "        VALUES ('aaa', '&#8228;피아노', 100000)"
            + "]]></script>"
            )