Mybatis使用IN()查询出现的错误解决记录

问题描述

使用IN进行多个Id查询时,在数据库管理工具中测试时没问题的,后来放到项目里面,发现查的总是不对,项目中使用的是@Select注解,需要替换的部分是IN(#{ids})这样写的。
原代码如下:

    @Select("select oc_material_variable.id as material_variable_id,oc_material_variable.name,oc_material_variable.descr,oc_material_variable.example,oc_material_variable.min_length,oc_material_variable.max_length from oc_scan_variable,oc_material_variable\n" +
            "where oc_scan_variable.material_variable_id=oc_material_variable.id\n" +
            "and oc_scan_variable.material_id in (#{ids}) group by oc_scan_variable.material_variable_id")
    List<HashMap<String,Object>> getNeedValueByIds(String ids);

问题分析

查询很多博客说通过映射文件里for标签进行解决,其实不用这么麻烦,问题根本是占位符的书写问题,之前一直用的是#{},这种写法Mybatis会自动在需要替换的地方加上“”,假如我们这里的ids是1,2,3,那么使用#{}最后生成的代码就是IN("1,2,3"),显然会出现问题。

问题解决

解决办法就是使用${},占位符即可解决,这个占位符不会添加任何东西。