KSI일기장
Mybatis 동적 SQL( if, choose(when,oterwise), trim(where,set) ) 본문
마이바티스의 가장 강력한 기능 중 하나인 동적SQL을 처리하는 방법이다
1.if
동적SQL에서 가장 공통적으로 사용되는것으로 where의 일부로 포함될 수 있습니다
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
2.choose, when, otherwise
java에서 switch구문과 유사하며 Mybatis에서는 choose엘리먼트를 제공한다
<choose>는 switch를 <when>은 case를 의미한다
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
3.trim, where, set
prefix:실행할 쿼리의 <trim>문 안에 쿼리 가장 앞에 붙여준다
suffix:실행할 쿼리의 <trim>문 안에 쿼리 가장 뒤에 붙여준다
prefixOverrides:실행할 쿼리의 <trim>문 안 조건( <if> )이 true이면 prefixOverrides=" "안에 들어있는 해당 문자들을 자동으로 지워준다
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<trim prefix="WHERE" prefixOverrides="AND|OR">
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</trim>
</select>
'Spring' 카테고리의 다른 글
0509spring 게시물 댓글(1) 댓글조회 (댓글 DB테이블 생성, jsp,js포함) (0) | 2023.05.08 |
---|---|
0508spring 게시판(4) 글 작성, 수정 (0) | 2023.05.08 |
0428spring 마이페이지(3) 회원탈퇴 (1) | 2023.05.03 |
0428spring 마이페이지(2) 비밀번호변경(암호화) (0) | 2023.05.03 |
0502spring 게시판(3) 글 조회수 증가, 중복제거 (0) | 2023.05.02 |