MyBatis——sql

這個元素能夠被用來定義可重用的 SQL 代碼段,能夠包含在其餘語句中。它能夠被靜態地(在加載參數) 參數化. 不一樣的屬性值經過包含的實例變化. 好比:sql

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

這個sql片斷能夠被包含到其餘語句當中,如:code

<select id="selectUsers" resultType="map">
  select
    <include refid="userColumns"><property name="alias" value="t1"/></include>,
    <include refid="userColumns"><property name="alias" value="t2"/></include>
  from some_table t1
    cross join some_table t2
</select>

以上即爲調用id爲userColumns的sql,並將其中的${alias}都替換爲t一、t2。get

複雜版: 屬性值也能夠被用在 include 元素的 refid 屬性裏,如:table

<include refid="${include_target}"/>

或 include 內部語句中,如:select

${prefix}Table

調用sql,如:meta

<sql id="sometable">
  ${prefix}Table
</sql>

<sql id="someinclude">
  from
    <include refid="${include_target}"/>
</sql>

<select id="select" resultType="map">
  select
    field1, field2, field3
  <include refid="someinclude">
    <property name="prefix" value="Some"/>
    <property name="include_target" value="sometable"/>
  </include>
</select>

分析:
select語句中,先使用include標籤直接調用id爲someinclude的sql的代碼塊; 以後給${prefix}元素複製爲Some,${include_target}元素賦值爲sometable; id爲someinclude的代碼塊中有包含了一個include標籤,咱們已經經過元素賦值${include_target}變爲sometable,所以內部的include將直接調用id爲sometable的代碼塊。map

初步思考:
使用sql代碼塊,能夠大量減小重複代碼的編寫。好比在根據id或name查詢行時,咱們咱們的select域都是相同的,所以能夠用sql代碼塊進行封裝,再直接調用include標籤便可。d3

相關文章
相關標籤/搜索