原文鏈接
http://opensource.atlassian.com/confluence/oss/display/IBATIS/How+do+I+reuse+SQL-fragments
When writing SqlMaps, you often encounter duplicate fragments of SQL, for example a FROM-clause or constraint-statement; iBATIS offers a simple yet powerful tag to reuse them. For the sake of simplicity, let's assume we want to get some items and we want to do a count on them.
Normally, you would write something like this:
當我們寫SqlMaps的時候,經常會碰到重復的SQL片段,例如From語句或者約束條件;iBATIS提供了一個強大的標簽來復用這些重復片段,簡單舉例,我們想檢索一些字段,并且想統計它們。
通常情況下,你會這樣寫:
xml 代碼
-
<
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
>
?? ??
-
??
?To eliminate this duplication, we use the tags 【sql】 and 【include】. The 【sql】-tag contains the fragment to reuse, the 【include】-tag to include such a fragment:
為了消除重復片段,我們使用【sql】和【include】標簽。【sql】標簽用來包含重復片段,【include】標簽用來引入片段:
?xml 代碼
-
<
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
>
?? ??
-
??
?The 【include】-tag is namespace-aware so you can refer to fragments even when they are located in another map (however, due to the way iBATIS loads the SqlMaps, the included fragment should be loaded before the including statement).?
【inclued】標簽是一個命名空間可知的,所以你可以引入其他map的片段.(但是,因為iBATIS引入SqlMap的順序,被引入的片段,要優先于欲引入的sql部分被導入)
The fragments are included and processed on query-execution so parameters can be used too:
重復片段在查詢執行時被引入和執行,所以參數依然可以使用:
?xml 代碼
-
<
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
>
?? ??
-