반응형
- MyBatis를 이용해서 같은 형태의 분류만 다른 쿼리를 사용해야 할 때 id만 다르게 쿼리를 여러 개 작성해야 할 때가 있다.
- 이러할 때에는 동적 태그를 이용해서 하나의 쿼리문으로 여러 경우의 다른 쿼리를 전송할 수 있다.
- MyBatis의 동적 태그에는 if, choose(when, otherwise), where, trim, foreach가 있다.
1. if
<if test="조건식">
//내용
</if>
2. choose, when, otherwise
<choose>
<when test="조건식">
//내용
</when>
//...
<otherwise>
//내용
</otherwise>
</choose>
3. where
- 내부의 내용이 없으면 where절을 없애준다.
select * from spring_board
<where>
boardnum=#{boardnum}
</where>
select * from spring_board
<where>
<if test="boardnum > 10">
boardnum=#{boardnum}
</if>
</where>
4. trim
- prefix, prefixOverrides : 앞에 붙이는 거, 앞에 것을 자르는 것
- suffix, suffixOverrides : 뒤에 붙이는 거, 뒤에 것을 자르는 것
// b를 자르고 a를 앞에 붙여넣음
<trim prefix="a " prefixOverrides="b">
b 내용
</trim>
//결과 : a 내용
5. foreach
- List, 배열, Map 등을 이용해서 루프를 처리
<foreach collection="컬렉션명" index="키의 이름" item="값의 이름">
// 내용
</foreach>
// map : {"T" :"TTTT", "C":"CCCC", "W":"WWWW"}
<foreach collection="map" index="key" item="val">
#{key} and #{val}
</foreach>
// 결과 : T and TTTT C and CCCC W and WWWW
6. sql, include
- <sql> 태그는 다른 구문에서 재사용 가능한 SQL 구문을 정의할 때 사용
<sql id="아이디명">
사용할 쿼리
</sql>
- <include> 태그는 같은 파일 내에 정의해둔 <sql> 태그 내의 쿼리들을 불러올 수 있게 해 준다.
<include refid="아이디명"></include>
<sql id="practice">
select * from practice where a=#{a}
</sql>
<include refid="pratice"></include>
7. 예시
- 제목과 작성자로 app을 검색했을 때
- typeArr = {"T", "W"}, keyword = "app"
select * from spring_board where ((boardtitle like('%app%')) or (userid like('%app%'))) and
0 < boardnum order by boardnum desc limit #{startrow}, #{amount}
8. <![CDATA[ ]]>
- <![CDATA[ -쿼리- ]]> : 이 안에 있는 쿼리에서 <> 태그를 무시하고 쿼리로 사용 가능하다.
<![CDATA[
0 < boardnum order by boardnum desc limit #{startrow}, #{amount}
]]>
반응형
'웹개발 > Spring' 카테고리의 다른 글
[Spring] Spring에서의 REST 컨트롤러 사용 및 JSON 객체를 이용한 REST 방식의 Ajax 이용 (0) | 2022.08.04 |
---|---|
[Spring] REST(Representational State Transfer), JSON(JavaScript Object Notation), Ajax(jQuery) (0) | 2022.08.03 |
[Spring] Controller의 매개변수 사용, redirect, Controller Test 환경 (0) | 2022.07.15 |
[Spring] 명명 규칙, Service, domain (0) | 2022.07.13 |
[Spring] Exception 처리, 스프링 MVC 프로젝트의 기본 구성(3-tier) (0) | 2022.07.06 |