๑ `⌃´ ๑

동적 쿼리는 상황에 따라 다른 쿼리문을 실행하게 하는 쿼리로, 자바의 조건문을 생각하면 이해하기 쉽다.

Java와 MyBatis는 표기법이 약간씩 다르기 때문에 주의가 필요하다.

 

<if>

test 속성을 만족할 경우에 해당 쿼리문을 실행한다.

	<insert id="join" parameterType="com.spring.main.dto.BoardDTO">
		INSERT INTO member(id,pw,name,email)
			<if test="!email.equals('')">
				VALUES(#{id},#{pw},#{name},#{email})
			</if>
			<if test="email.equals('')">			
				VALUES(#{id},#{pw},#{name},'이메일 없음')
			</if>
	</insert>

test 속성에는 true/false를 반환할 boolean 타입의 조건이 필요하다.

 

 

<choose> / <when> / <otherwise>

Java의 if else 구문과 비슷하다. if 태그만을 단독으로 사용했을 때에는 하나의 조건에 대한 판단만 가능하며 else 의 경우를 판단할 수 없다. 이 때 choose 태그를 사용하며, 세 태그가 각각 if / if else / else 의 기능을 수행한다고 보면 된다.

	<insert id="join" parameterType="com.spring.main.dto.BoardDTO">
		INSERT INTO member(id,pw,name,email)
			<choose>
				<when test="!email.equals('')">
					VALUES(#{id},#{pw},#{name},#{email})
				</when>
				<otherwise>			
					VALUES(#{id},#{pw},#{name},'이메일 없음')
				</otherwise>
			</choose>
	</insert>

 

 

<where>

db의 where 구문과 동일한 역할이다. 조건에 부합할 경우에만 where 태그를 사용한다.

	<select id="list" resultType="com.spring.main.dto.BoardDTO">
		SELECT id,name,email FROM member
		<where>
			<if test="!param2.equals('') and param1 == 'id'">
				id LIKE CONCAT('%',#{param2},'%')
			</if>
			<if test="!param2.equals('') and param1 == 'name'">
				name LIKE CONCAT('%',#{param2},'%')
			</if>
			<if test="!param2.equals('') and param1 == 'email'">
				email LIKE CONCAT('%',#{param2},'%')
			</if>
		</where>
	</select>

 

* 참고 : 문자열을 합치는 방식(DB마다 다름)

[MS-SQL] '%'+#{keyword}+'%'
[ORACLE] '%'||#{keyword}||'%'
[MY SQL] CONCAT('%',#{keyword},'%')

 

 

<foreach>

C태그의 그 forEach와 유사하게 사용된다. list 형태로 데이터를 전달받는다.

	<select id="multi" parameterType="list" resultType="com.spring.main.dto.BoardDTO">
		SELECT id,name,email FROM member
		<where>
			name IN
			<foreach collection="list" item="item" open="(" separator="," close=")">
				#{item}
			</foreach>
		</where>
	</select>

collection : 값 목록을 가진 객체. 주로 List 나 배열

item : collection 내의 개별 값을 나타내는 변수들의 이름.(배열이나 리스트 덩어리의 이름)

open : 해당 블럭을 시작할 때 사용하는 기호. 주로 '(' 사용

close : 해당 블럭을 끝낼 때 사용하는 기호. 주로 ')' 사용

separator : 각 item들을 구분할 분리자 기호. 주로 ',' 사용

 

* OR 여러개 사용할 경우 IN을 사용하는 것이 더 효율적이라 IN 사용

 

 

<set>

update 문에서 동적으로 사용 가능. if 문만 사용하면 콤마(,) 때문에 에러가 발생할 수 있음

	<update id="update" parameterType="hashmap">
		UPDATE member
		<set>
			<if test="!pw.equals('')">
				pw = #{pw},
			</if>
			<if test="!email.equals('')">
				email = #{email},
			</if>
			<if test="!name.equals('')">
				name = #{name}
			</if>
		</set>
		WHERE id = #{id}
	</update>

 

'Spring' 카테고리의 다른 글

AOP(Aspect Oriented Programming)  (0) 2022.09.05
Model1, Model2, MVC 패턴  (0) 2022.07.18
JSP Templates 셋팅  (0) 2022.07.18
Ajax  (0) 2022.05.27
root-context 에 파일업로드 설정하기  (0) 2022.05.26
🎵 Playlist
loading...
00:00 / 00:00