2012. 10. 17. 14:35
SqlMaps를 작성할때, 종종 SQL의 일부가 중복되곤한다. 예를 들어, FROM절이나 제약조건등이 그렇다. iBATIS는 이러한 중복되는 SQL문의 일부를 재사용하기 위한 강력한 태그를 제공한다. iBATIS사용시 대개 다음처럼 작성할것이다.
<select id="selectItemCount" resultClass="int"> SELECT COUNT(*) AS total FROM items WHERE parentid = 6 </select> <select id="selectItems" resultClass="Item"> SELECT id, name FROM items WHERE parentid = 6 </select>
여기서는 FROM절 이하가 모두 중복이다. 이 중복을 제거하기 위해서, <sql> 과 <include> 태그를 사용한다. <sql> 태그는 재사용하기 위한 조각을 포함한다. <include> 태그는 이러한 조각을 포함한다.
<sql id="selectItem_fragment"> FROM items WHERE parentid = 6 </sql> <select id="selectItemCount" resultClass="int"> SELECT COUNT(*) AS total <include refid="selectItem_fragment"/> </select> <select id="selectItems" resultClass="Item"> SELECT id, name <include refid="selectItem_fragment"/> </select>
<include> 태그는 명명공간을 인식한다. 그래서 당신은 다른 map에 위치한 조각들도 참조할수 있다(어쨌든 iBATIS가 SqlMaps를 로드하는 방식에 따라, 포함된 조각은 statement를 포함하기 전에 로드될것이다). 조각은 파라미터처럼 사용될수 있기 때문에 쿼리-수행시 포함되고 처리된다.
<sql id="selectItem_fragment"> FROM items WHERE parentid = #value# </sql> <select id="selectItemCount" parameterClass="int" resultClass="int"> SELECT COUNT(*) AS total <include refid="selectItem_fragment"/> </select> <select id="selectItems" parameterClass="int" resultClass="Item"> SELECT id, name <include refid="selectItem_fragment"/> </select>
'FrameWork' 카테고리의 다른 글
Spring + mybatis 환경에서 xml 파일 변경시 서버 재시작 없이 반영 방법 (2) | 2019.03.24 |
---|---|
[Spring, Log] 로그가 안보일때, 쿼리가 안나타날때 로그 출력하는 방법 (0) | 2019.03.23 |
iBatis에서 AutoResultMap Error 해결방법 (0) | 2015.03.04 |