티스토리 뷰

Daylogs/DB

Reuse sql fragments in IBATIS

ohgyun 2009. 1. 20. 11:43
http://openframework.or.kr/JSPWiki/Wiki.jsp?page=ReuseSQLFragments

http://opensource.atlassian.com/confluence/oss/pages/viewpage.action?pageId=707

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>

반응형
댓글
공지사항