How can I reuse an SQL fragment with parameters?

Jin Kwon picture Jin Kwon · Nov 13, 2014 · Viewed 7.3k times · Source

I'm intending to make a fragment for reusing with parameters.

<insert ...>
  <selectKey keyProperty="id" resultType="_long" order="BEFORE">
    <choose>
      <when test="_databaseId == 'derby'">
        VALUES NEXT VALUE FOR SOME_ID_SEQ
      </when>
      <otherwise>
        SELECT SOME_ID_SEQ.NEXTVAL FROM DUAL
      </otherwise>
    </choose>
  </selectKey>
  INSERT INTO ...
</insert>

Can I make an SQL fragment using parameters?

<sql id="selectKeyFromSequence">
  <selectKey keyProperty="id" resultType="_long" order="BEFORE">
    <choose>
      <when test="_databaseId == 'derby'">
        VALUES NEXT VALUE FOR #{sequenceName}
      </when>
      <otherwise>
        SELECT #{sequenceName}.NEXTVAL FROM DUAL
      </otherwise>
    </choose>
  </selectKey>
</sql>

So that I can reuse them like this?

<insert ...>
  <include refid="...selectKeyFromSequence"/> <!-- How can I pass a parameter? -->
  INSERT INTO ...
</insert>

Is this possible?

Answer

Vlasta Dolejs picture Vlasta Dolejs · Feb 15, 2016

As of version 3.3.0 you can do it like this:

<sql id="myinclude">
  from ${myproperty}
</sql>

<include refid="myinclude">
  <property name="myproperty" value="tablename"/>
</include>

See section SQL in http://www.mybatis.org/mybatis-3/sqlmap-xml.html