iBATIS如何复用SQL片段

原文链接
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>    

你可能感兴趣的:(ibatis)