关于在mybatis中将table名称作为参数传递

About passing table name as a parameter in mybatis

当我尝试将 table 名称作为参数传递给 sql 映射时,例如

public MatchResult get(long id, String tablename);

映射器xml:

<select id="get" parameterType="long" resultType="myresult">
    select * from  where id=#{0}
</select>

但是不行。

${} 根据我的测试不支持参数索引。 您可以使用 Param 注释在映射器中指定参数名称 API声明。

public MatchResult get(long id, @Param("tablename") String tablename);

映射器xml:

<select id="get" resultType="myresult">
    select * from ${tabelname} where id=#{0}
</select>

如果您不想要 IBatis/MyBatis 特定注释 Param,另一种方法是使用您自己的对象 class 或地图作为参数在你的映射器 API 声明中。

以地图为例,你的javaAPI可能是:

public MatchResult get(Map<String, Object> params);

映射器 xml 语句可以是:

<select id="get" parameterType="map" resultType="myresult">
    select * from ${tablename} where id=#{id}
</select>

并在调用 API.

之前将 id 和表名放入具有键 "id" 和 "tablename" 的映射中