ibatis里面复用sql片段

原文链接

http://opensource.atlassian.com/ ... 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提供了一个强大的标签来复用这些重复片段,简单举例,我们想检索一些字段,并且想统计它们。

通常情况下,你会这样写:

<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】标签用来引入片段:

<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:

重复片段在查询执行时被引入和执行,所以参数依然可以使用:

<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>    


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值