mybatis 동적 쿼리

정태규·2023년 3월 2일
0

sql , include

공통부문을 sql로 정의하고 include로 포함시켜 재사용.

<select id = "select" parameterType ="int" resultType="BoardDto>
  SELECT bno,title,content,writer,view_cnt,comment_cnt,reg_date
  FROM board
  WHERE bno = #{bno}                                               
</select>    
<select id ="selectPage" parameterType ="map" resultType="BoardDto">
  SELECT bno,title,content,writer,view_cnt,comment_cnt,reg_date
    FROM board
  ORDER BY reg_date DESC, bno DESC
  LIMIT #{offset},#{pageSize}
</select>  

이러한 두 쿼리가 있다. 이 두 쿼리는 앞에부분이 공통으로 겹친다. 공통으로 겹치는 부분을 다시한번 쓰기보다는 등록해 놓으면 다른 쿼리에서 다시 한번 사용가능하다.

<sql id ="selectFromBoard">
	select bno,title,content,writer,view_cnt,comment_cnt,reg_date
    FROM board
</sql>

<select id ="select" parameterType="int" resultType="BoardDto">
	<include refid="selectFromBoard"/>
    where bno = #{bno}
</select>

<select id ="selectPage" parameterType="map" resultType="BoardDto">
	<include refid="selectFromBoard"/>
    ORDER BY reg_date DESC,bno DESC
    LIMIT #{offset},#{pageSize}
</select>

위에 구문을 보면 공통되는 부문을 sql문으로 정의해주었다.
사용할 구문에서는 include로 포함만 시켜주면 된다.

if

if문은 일반적인 언어에서 쓰이는 것처럼 똑같다.

<select id="searchResultCnt" parameterType="SearchCondition" resultType = "int">
	SELECT count(*)
    FROM board
    WHRER true //true를 써준건 뒤에 AND때문이다. 만약 True가 없다면 where and 이기 때문에 sql 문법 오류가 나타난다.
    <if test='option =="A"'>
    	AND(title LIKE concat('%',#{keyword},'%'))
        OR (content LIKE concat('%',#{keyword},'%'))
    </if>
    .
    .
    .
</select>    

choose ,when

if-else 같은 구문을 사용하고 싶다면 choose-when-otherwise를 사용한다.

<select id="searchResultCnt" parameterType="SearchCondition" resultType="int">
	SELECT count(*)
    FROM board
    WHERE true
    <choose>
    	<when test='option'=="T"`>
        	AND title LIKE concat('%',#{keyword},'%')
        </when>
        <when test='option=="w"'>
        	AND writer LIKE concat('%',#{keyword},'%')
        </when>
        <otherwise>
        AND(title LIKE concat('%',#{keyword},'%'))
        OR(content LIKE concat('%',#{keyword},'%'))
        </otherwise>
     </choose>
<select>     

% , _

mybatis에서 sql문 작성할때
%는 0이거나 그이상 다와도 됨.
_는 1개만 와야함.

예) title% --> title,title1,title12 다가능
title_ --> title(x), title12(x), title1 가능

참고로 oracle에서는 %와?를 쓴다. ?가 1개 올때

foreach

값이 여러개가 들어올때 foreach를 사용한다.

<select id ="getSelected" resultType = "BoardDto">
	SELECT bno,title,content,writer,view_cnt,comment_cnt,reg_date
    FROM board
    where bno IN
    <foreach collection ="array" item="bno" open=")" separator=",">
    	#{bno}
    </foreach> //where bno in (1,2,3,...)
    OREDER BY reg_date DESC, bno DESC
 </select>   

0개의 댓글