오늘은 몰랐으면 내일은 알면 된다

2022-12-16 (1) MyBatis 동적 SQL 본문

Java/JAVA 개발자 양성과정

2022-12-16 (1) MyBatis 동적 SQL

마스터피쓰 2022. 12. 16. 10:24

다음의 네가지 태그들을 이용한다.

  1. if
  2. choose(when, otherwise)
  3. trim(where, set)
  4. foreach

 

[if]

if는 test라는 속성과 함께 특정한 조건이 true가 되었을 때 포함된 SQL을 사용하고자 할 때 작성한다.

예시로, 검색조건이 T이면 제목으로 검색하고, 검색조건이 W이면 작성자ID로 검색한다고 해보자.

검색 조건값과 함께 test의 조건값도 전달되어야 하기 때문에 parameter는 map 형식이 되어야 한다.

Map<String, String> map = new HashMap<>();
map.put("opt", "T");
map.put("word", "%가%");
List<RepBoard> list = session.selectList("매퍼네임스페이스.a", map);
<select id="a" parameterType="map" resultType="RepBoard">
	SELECT * FROM rep_board
    WHERE
        <if test="opt == 'T'">
            (board_title LIKE '%'||#{keyword}||'%')
        </if>
        <if test="opt == 'W'">
            (board_id LIKE '%'||#{keyword}||'%')
        </if>
</select>

 

[otherwise]

if와 달리, choose는 여러 상황들 중 하나의 상황에서만 동작한다. otherwise는 모든 when 조건이 충족되지 않을 경우에 사용한다.

<choose>
<when test="opt == 'T'">
	(board_title like'%'||#{keyword}||'%')
</when>
<when test="opt == 'C'">
	(board_content like'%'||#{keyword}||'%')
</when>
<when test="opt == 'W'">
	(board_id like'%'||#{keyword}||'%')
</when>
<otherwise>
	(board_title like'%'||#{keyword}||'%' OR board_content like'%'||#{keyword}||'%')
</otherwise>
</choose>

 

[set]

: 만약 첫번째 조건만 만족되어 뒤에 , 가 남는 상황이라면, set 태그가 알아서 , 를 삭제해서 SQL 구문 오류가 나지 않도록 한다.

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

 

[바인딩 변수 ? 를 대신하는 문법]

#{파라미터}

#{맵.키}

#{빈.프로퍼티}

?를 대신하는 문법이기 때문에 값의 위치에만 올 수 있다. 따라서 like 연산시에는 "%가%"와 같이 %를 붙인 문자열을 전달해야한다.

<select parameterType="string">인 경우 : #{id} 또는 #{aaa} 등 아무 이름이라도 상관없음
<select parameterType="map">인 경우 : #{opt} #{word} 등의 key값만 사용가능
<select parameterType="RepBoard">인 경우 : #{boardNo} #{boardTitle} 등의 멤버값만 사용가능

그러나 %를 붙이는것마저 귀찮기 때문에 새로운 문법이 나왔는데, $ 표시이다.

 

[문자열역할의 문법 ${  }]

ORDER BY boardNo ASC
ORDER BY boardNo DESC

ORDER BY boardNo ${orderType}
ORDER BY boardNo #{orderType} 사용불가

자세한 문법은 아래를 참고하자.

https://mybatis.org/mybatis-3/dynamic-sql.html

 

mybatis – MyBatis 3 | Dynamic SQL

Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilities. If you have any experience with JDBC or any similar framework, you understand how painful it is to conditionally concatenate strings of SQL together, mak

mybatis.org

'Java > JAVA 개발자 양성과정' 카테고리의 다른 글

2022-12-16 (3) Transaction  (0) 2022.12.16
2022-12-16 (2) AOP  (0) 2022.12.16
2022-12-15 (4) REST  (0) 2022.12.15
2022-12-15 (3) 스프링 MVC 프로젝트의 기본 구성  (0) 2022.12.15
2022-12-15 (2) 트랜잭션 처리  (0) 2022.12.15