当我们写SqlMaps的时候,经常会碰到重复的SQL片段,例如From语句或者约束条件;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>
为了消除重复片段,我们使用【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>
【inclued】标签是一个命名空间可知的,所以你可以引入其他map的片段.(但是,因为iBATIS引入SqlMap的顺序,被引入的片段,要优先于欲引入的sql部分被导入)
重复片段在查询执行时被引入和执行,所以参数依然可以使用:
<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>
转自:http://sinokaka.iteye.com/blog/39274