mybatis where 中in的使用

當咱們使用mybatis時,在where中會用到 in 如:sql

where name in ('Jana','Tom');數組

咱們能夠在sql中直接寫 name in ('Jana','Tom') 或者 name in (${names})  (備註:String names = "'Jana','Tom'"; 使用$時會引發sql注入安全問題)安全

可是咱們沒法在sql中直接寫 name in (#{names});mybatis

會報參數個數錯誤,由於'Jana','Tom'會被解析成兩個傳參函數

String[] names={"Jana","Tom"};spa

此時要用foreach函數:code

 

name in
<foreach collection="names" item="name" index="index" open="(" close=")" separator=",">
    #{name}
</foreach>

 

解析爲:blog

name in (?,?),而後利用names傳入參數string

關於參數的形式,能夠是數組形式能夠是List形式:it

1.當只傳入names變量時,collection必須指定array或list類型:

public List<User> findInfos(String[] names);
<select id="findInfos" resultMap="UserMap">
    SELECT * FROM t_user
    WHERE id IN
    <foreach collection="array" item="name" index="index" open="(" close=")" separator=",">
      #{name}
    </foreach>
</select>
public List<User> findInfos(List<String> names); 
<select id="findInfos" resultMap="UserMap"> SELECT * FROM t_user WHERE id IN <foreach collection="list" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach> </select>

 注意:array傳入的時候parameterType能夠是"Integer[]" ,能夠是"int[]",但不能夠是"String[]"

報錯 Could not resolve type alias 'string[]'. Cannot find class: string[]

2.當有其餘變量時,利用map傳入參數集時,能夠直接將變量寫在collection中

Map<String,Object> params = new HashMap<>();
params.put("class",class);
params.put("names",names);
<select id="findInfos" resultMap="UserMap"> SELECT * FROM t_user WHERE id IN <foreach collection="names" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach> </select>
相關文章
相關標籤/搜索