我在*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);
答案 0 :(得分:1)
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。