mybatis sql 文字的变量语法是什么

What is the mybatis sql variable syntax for literals

我在 *Dao.java 文件中有一堆 sql 看起来像这样的文件:

select * from table where id = #{id};

如果我只需要 1 条 ID 为 int 的记录,它就可以正常工作。但是,我想写这样的声明:

select * from table where id in (#{idList});

如何更改 #{idList} 以便列表(作为串联 ID 的字符串传入)不会在实际结果的 sql 语句中用引号引起来?

现在生成的 sql 类似于:

select * from table where id in ('1,2,3,4,5');

我希望它是

select * from table where id in (1,2,3,4,5);

MyBatis 使用${variable} 来支持文字。对于您的情况,sql 可能如下所示。

select * from table where id in (${idList})

但请记住,${} 无法阻止 sql injection 如果您可以确保 sql injection 对您的情况不可行,那么很好。

另一种方法是使用 foreach 来支持 in 闭包 MyBatis 3。详情请参考http://mybatis.github.io/mybatis-3/dynamic-sql.html#foreach

对于您的情况,sql 可能是:

select * from table where id in
<foreach item="item" index="index" collection="list"
    open="(" separator="," close=")">
    #{item}
</foreach>

并且参数类型是List,但不是串联的ID字符串。