包含的SQL片段不替换参数

时间:2014-11-20 05:51:54

标签: mybatis ibatis

我的mapper界面看起来像这样。

public interface CommonMapper {
    long selectSequenceNumber(String sequenceName);
}

我准备的sql mapper看起来像这样。

<sql id="sequenceNumber">
  <choose>
    <when test="_databaseId == 'derby'">
      VALUES NEXT VALUE FOR #{sequenceName}
    </when>
    <otherwise>
      SELECT #{sequenceName}.NEXTVAL FROM DUAL
    </otherwise>
  </choose>
</sql>
<select id="selectSequenceNumber" resultType="_long">
  <!--<include refid="....mapper.CommonMapper.sequenceNumber"/>-->
  <include refid="sequenceNumber"/>
</select>

当我测试mapper #{sequenceName}时,part未被替换为。

14:36:09.492 [main] DEBUG ....selectSequenceNumber - ==>  Preparing: VALUES NEXT VALUE FOR ? 
14:36:09.724 [main] ERROR ....PersistenceTests - failed to apply function for SqlSession
org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at line 1, column 23.
### The error may exist in .../CommonMapper.xml
### The error may involve ....CommonMapper.selectSequenceNumber
### The error occurred while executing a query
### SQL: VALUES NEXT VALUE FOR ?
### Cause: java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at line 1, column 23.

这是正常的吗?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您需要使用字符串替换${sequenceName}而不是使用#{}设置参数,以便在查询中直接放置字符串(例如,用于提供对象名称,动态SQL等...)

<sql id="sequenceNumber">
  <choose>
    <when test="_databaseId == 'derby'">
      VALUES NEXT VALUE FOR ${sequenceName}
    </when>
    <otherwise>
      SELECT ${sequenceName}.NEXTVAL FROM DUAL
    </otherwise>
  </choose>
</sql>
<select id="selectSequenceNumber" resultType="_long">
  <!--<include refid="....mapper.CommonMapper.sequenceNumber"/>-->
  <include refid="sequenceNumber"/>
</select>