3. Back-end/3-2. Spring MVC - 남궁성

SpringMVC - [ MyBatis 동적 쿼리 ]

yunyj99 2023. 4. 4. 00:10

1. <sql>과 <include>

 공통 부분을 <sql> 로 정의하고, <include>로 포함시켜 재사용할 수 있다.

 

예를 들어 아래와 같이 두 개의 sql문이 있을 때

<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="select" parameterType="int" 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>로 빼내어 사용할 수 있다.

<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>

 

 

 

 


2. <if>

사실 아래의 예시에서 option은 셋 중 하나이므로 if보단 choose가 더 어울린다.

<select id="searchResultCnt" parameterType="SearchCondition" resultType="int">
    SELECT count(*)
    FROM board
    WHERE true	-- 뒤에 AND가 오기 때문에 true로 시작
    <if test='option=="A"'>
        AND (title	LIKE concat('%', #{keyword}, '%')
        OR content	LIKE concat('%', #{keyword), '%')) 
    </if> 
    <if test='option=="T"'>
        AND title LIKE concat('%', #{keyword}, '%')
    </if>
    <if test='option=="W"'>
        AND writer LIKE concat('%', #{keyword}, '%')
    </if>
</select>

 

 

 

 


3. <choose> <when>

choose 에서는 when에서 true인 조건을 찾으면 뒤의 조건은 확인하지 않는다.

일치하는 조건이 없으면 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>

 

 

 


4. <foreach>

아래에서 foreach안의 문장은 괄호( )를 시작과 끝으로 구분자 , 를 줘서 만들어준다.

collection 값이 array 이므로 Integer[] 과 같은 배열 값을 인자로 넘겨줄 수 있다.

즉 넘어온 배열 값이 {1,2,3} 이면 => (1, 2, 3) 이런 식으로 만들어줘서 bno IN (1, 2, 3) 과 같은 문장이 된다.

<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="(" close=")" separator=",">
		#{bno}
	</foreach>
	ORDER BY reg_date DESC, bno DESC 
</select>

 

 

 

 


와일드카드

MySQL에서 와일드 카드는 %(0~여러 글자) _(한 글자) 가 있다.

 


참조

https://fastcampus.co.kr/dev_academy_nks

 

스프링의 정석 : 남궁성과 끝까지 간다 | 패스트캠퍼스

국비지원 조기 마감 신화, 베스트셀러 'JAVA의 정석'의 저자 남궁성의 Spring 강의입니다! 오픈톡방과 카페에서 평생 AS를 제공하며 완강과 취업까지 도와드립니다. 지금 할인가로 확인하세요!

fastcampus.co.kr