iBATIS如何複用SQL片段(翻譯)

來源:互聯網
上載者:User

原文連結

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>  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.