Posts [개발자 블로그] MyBatis의 활용
Post
Cancel

[개발자 블로그] MyBatis의 활용

MyBatis의 활용

  • #{}과 ${}의 차이
  • <bind> 문법
    • 외부에서 전달된 파라미터를 이용하여 변수 생성하는 엘리먼트, 동적 쿼리 변수를 생성할 때 사용한다.
    • 형식
    1
    2
    3
    
      <select | insert | update | delete><br>
      <bind name="지정할 변수이름" value="파라미터 값+부가 옵션"/><br>
      </select | insert | update | delete><br>
    
    • 예제
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
      <select id="getTest" resultType="board">
      SELECT * FROM board
      <bind name="ids" value="'%'+id+'%'"/>
      <bind name="subjects" value="'%'+subject+'%'"/>
      <where>
      <if test="id != null"> AND id like #{ids}</if>
      <if test="subject != null"> AND subject like #{subjects} </if>
      </where>
      </select>
    

<where> 문법 - 추가 쿼리 문의 내용을 문 안에 작성하면 첫 조건이 AND로 시작할지라도 WHERE로 치환되어 쿼리가 수행 된다. - 형식

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
~~~
<select id="id">
SELECT * FROM table
<where>
추가 SQL
</where>
</select>
~~~

· 예제

~~~
<select id="getTest" resultType="board">
SELECT * FROM baord
<where>
<if test="id != null">AND id = #{id} </if>
<if test="subject != null">AND subject = #{subject} </if>
</where>
</select>
~~~

HashMap을 이용한 동적 쿼리 생성

출처

This post is licensed under CC BY 4.0 by the author.