ibatis(mybatis) 쿼리 xml을 작성할때 조건문이 필요할 경우가 생긴다.
ibatis(mybatis)의 장점은 조건을 주면서 동적쿼리를 생성할수 있다는 장점이 있다.
즉, 프로시저를 사용하지 않아도 어느정도의 출력이 가능하다는 이야기임.
다음과 같은 테이블이 있다고 가정하자
– board
| id | int |
| title | varchar |
| content | text |
| create_id | varchar |
| update_id | varchar |
위의 기준으로 생성된 테이블에서 예를들기 위해 몇가지 조건에 따라 비교를 하도록 하겠음
1. update_id null/not null 체크 조건문
– ibatis(isNull / isNotNull)
|
1
2
3
4
5
6
|
<isNull property="update_id"> 조건절 </isNull><isNotNull property="update_id"> 조건절 </isNotNull> |
-mybatis(if / choose when otherwise)
|
1
2
3
4
5
6
|
<if test="update_id == null"> 조건절</if><if test="update_id != null"> 조건절</if> |
또는
|
1
2
3
4
5
6
7
8
|
<choose> <when test="update_id == null"> null 조건절 </when> <otherwise> not null 조건절 </otherwise></choose> |
2. update_id 공백유무 체크 조건문
– ibatis(isEmpty / isNotEmpty)
|
1
2
3
4
5
6
|
<isEmpty property="update_id"> 조건절</isEmpty><isNotEmpty property="update_id"> 조건절</isNotEmpty> |
-mybatis(if / choose when otherwise)
|
1
2
3
4
5
6
|
<if test="update_id == ''"> 조건절</if><if test="update_id != ''"> 조건절</if> |
또는
|
1
2
3
4
5
6
7
8
|
<choose> <when test="update_id == ''"> 공백일경우 조건절 </when> <otherwise> 공백 아닐경우 조건절 </otherwise></choose> |
mybatis의 공백조건 체크를 위와같이 조건을 주었는데도 체크가 되지 않을 경우에
하단 내용 처럼
쌍따옴표(“”) -> 홑따옴표(”) and 홑따옴표(”) -> 쌍따옴표(“”)로 변경을 해주자
문자열쪽에서 문제가 발생하는거 같음
3. id(숫자) 비교체크 조건문
– ibatis(isGreaterThan/isGreaterEqual/isLessThan/isLessEqual)
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<isGreaterThan property="id" compareValue="3">3보다 크다</isGreaterThan><isGreaterEqual property="id" compareValue="3">3보다 크거나 같다</isGreaterEqual><isLessThan property="id" compareValue="3"> 3보다 작다</isLessThan><isLessEqual property="id" compareValue="3">3보다 작거나 같다</isLessEqual> |
– mybatis(if/choose when otherwise)
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<if test='id > 3'> 3보다 크다</if> <if test='id >= 3'> 3보다 크거나 같다</if><if test='id < 3'> 3보다 작다</if><if test='id <= 3'> 3보다 작거나 같다</if> |
또는
|
1
2
3
4
5
6
7
8
9
10
11
|
<choose> <when test='id > 3'> 3보다 크다 </when> <when test='id == 3'> 3이다 </when> <when test='id < 3'> 3보다 작다 </when></choose> |
4. 검색 조건 선택후 검색버튼 클릭했을경우라고 가정
(문자열) 비교체크 조건문
– ibatis(isEqual / isNotEqual + compareValue)
|
1
2
3
4
5
6
|
<isEqual property="search_key" compareValue="title"> 조건절</isEqual><isNotEqual property="search_key" compareValue="content"> 조건절</isNotEqual> |
– mybatis는 공백조건의 경우와 동일하므로 생략
위와같이 비교를 들 수 있을 것이다.
본인의 생각으로
ibatis는 일일이 태그를 조건문 갯수에 따라 추가를 해줘야 하는 번거로움이 있는 반면,
mybatis는 JSTL처럼 일반적인 방식으로 사용을 해줄수 있어 라인수도 줄고 동적쿼리 작성하는데 코드작성이 좀더 수월한거 같다.
※ 만약 하나 이상의 조건을 mybatis에서 줄경우
&& = and
|| = or
로 하여서 여러개의 property로 비교가 가능하다.