sql

这个元素可以被用来定义可重用的 SQL 代码段,可以包含在其他语句中。它可以被静态地(在加载参数) 参数化. 不同的属性值通过包含的实例变化. 比如:

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

这个 SQL 片段可以被包含在其他语句中,例如:

  1. <select id="selectUsers" resultType="map">
  2. select
  3. <include refid="userColumns"><property name="alias" value="t1"/></include>,
  4. <include refid="userColumns"><property name="alias" value="t2"/></include>
  5. from some_table t1
  6. cross join some_table t2
  7. </select>

属性值也可以被用在 include 元素的 refid 属性里(

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

)或 include 内部语句中(

  1. ${prefix}Table

),例如:

  1. <sql id="sometable">
  2. ${prefix}Table
  3. </sql>
  4.  
  5. <sql id="someinclude">
  6. from
  7. <include refid="${include_target}"/>
  8. </sql>
  9.  
  10. <select id="select" resultType="map">
  11. select
  12. field1, field2, field3
  13. <include refid="someinclude">
  14. <property name="prefix" value="Some"/>
  15. <property name="include_target" value="sometable"/>
  16. </include>
  17. </select>