How can I reuse an SQL fragment with parameters?

不打扰是莪最后的温柔 提交于 2019-12-22 05:14:22

问题


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?


回答1:


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




回答2:


You cannot pass parameter to tags. There is a similar SO question, iBatis issue and a MyBatis issue.

Includes are in-lined when the xmls are parsed so the do not exist as their own once the startup process finishes (from MyBatis issue).

However, you can use variables inside tags. You do not pass it as a parameter but you can give it as a parameter to the function that has the include tag. You need to use the same variable name in all functions, i.e. #{sequenceName}.



来源:https://stackoverflow.com/questions/26900752/how-can-i-reuse-an-sql-fragment-with-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!