iBatis동적 쿼리 예
아래의 예처럼 4가지 형태의 심플한 동적 쿼리의 예 이다.
주의 할 것은 where 조건으로 한개 이상의 파라메터들 즉, 리스트 형태의 데이타를 파라메터로 사용하고 또한 리스트로 프리미티브 타입 즉, int or string 타입들의 컬렉션을 파라메터로 넘기고, iBatis의 맵퍼에서 <iterate > 를 사용하여 동적 SQL 구성을 해보는 것이다.
또하나 주의 할 것은 #의 의미와 $의 의미를 잘 이해해야 한다.
- # 는 prepaired statement 파라메터를 사용할 때 사용한다.
- $ 는 단순한 값의 치환자 로 생각하면 간단할 것 같다.
4)예는 Where 조건절을 아예 코드에서 작성하여 파라메터로 넘겨서 처리하는 단순한 구조이다.
만약 복잡한 것이 싫다면 이 방법 또한 간단하게 사용할 수 있겠다.
1) 카테고리 ID로 동적쿼리 select * from where categoryID=1 OR categoryID=2
<select id="DynamicIterate1" parameterClass="List"
resultClass="Categories">
select CategoryID,
CategoryName,
Description
from Categories
WHERE
<iterate open="" close="" conjunction=" OR ">
CategoryID = $[]$
</iterate>
</select>
<select id="DynamicIterate2"
parameterClass="List"
resultClass="Categories">
select CategoryID,
CategoryName,
Description
from Categories
WHERE CategoryID IN
<iterate open="(" close=")" conjunction=",">
$[]$
</iterate>
</select>
<select id="DynamicIterate3"
parameterClass="List"
resultClass="Categories">
select CategoryID,
CategoryName,
Description
from Categories
WHERE
<iterate open="" close="" conjunction=" OR ">
CategoryName LIKE '%$[]$%'
</iterate>
</select>
<statement id="DynamicIterate4"
parameterClass="string"
resultClass="Categories">
select CategoryID,
CategoryName,
Description
FROM Categories
<dynamic prepend="WHERE">
$param$
</dynamic>
</statement>
</statements>
</sqlMap>