IBATIS 2.0动态设置表名

时间:2014-02-19 13:42:39

标签: java sql spring ibatis

我想在Ibatis select标签中动态设置表名。

<select id="queryGetTopSongCount" parameterClass="java.lang.String" resultClass="java.lang.Integer">
    SELECT
    count(0)
    FROM 
    #toptable#
</select>

查询GetTopSongCount,如下所示

Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("toptable", "top_of_week_tab_6_2014");

int totalPagination=(Integer)getMainSqlMapClient().queryForObject(queryGetTopSongCount, toptable);

我收到以下错误

com.ibatis.common.jdbc.exception.NestedSQLException:   
--- The error occurred in resources/ibatis/song-sqlMap.xml.  
--- The error occurred while applying a parameter map.  
--- Check the song.queryGetTopSongCount-InlineParameterMap.  
--- Check the statement (query failed).  
--- Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''top_of_week_tab_6_2014'' at line 1

这个问题似乎与双引号有关。如何在没有双引号的情况下设置字符串参数?

2 个答案:

答案 0 :(得分:3)

我们需要用美元符号$ toptable $

包围参数,而不是用hash #toptable#包含参数。
<select id="queryGetTopSongCount" parameterClass="java.lang.String" resultClass="java.lang.Integer">
    SELECT
    count(0)
    FROM 
    $toptable$
</select>

答案 1 :(得分:0)

@Hasan Jamshaid 已经展示了解决方案

下面一个也可以

<select id="queryGetTopSongCount" parameterClass="java.lang.String" resultClass="java.lang.Integer">
    SELECT
    count(0)
    FROM 
    ${toptable}
</select>