首页 > 编程技术 > java

Mybatis 如何传入字符串参数,分割并遍历

发布时间:2022-1-21 16:34 作者:hanKongbin

如何传入字符串参数,分割并遍历

如前台传入字符串参数 

String str = "a,b,c,d,e,f";

现需将此参数作为查询语句的参数,

Select * from news where id in (${id})

使用该语句查询正常返回结果,但势必产生sql注入漏洞。

如修改为:

Select * from news where id in (#{id})

程序报错。

正确写为如下

id in
<foreach collection="str.split(',')"  item="item" index="index" open="(" separator="," close=")">#{item}</foreach>

Mybatis 传入分割字符串做参数

需求:更改指定一些客户的一个字段

设计:传参两个(一个需要更改字段,一个客户id字符串用","隔开)

问题:mybatis中sql语句里条件报错,原因是用了#{clientIds}传入sql中是字符串形式

where id in (#{clientIds}) 等于 where id in ("1,2,3,4") 报错

解决

方法1、客户id字符串在代码里分割成list,mybatis中list遍历

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

方法2、将字符串在mybatis里分割

<foreach collection="clientIds.split(',')" item="item" index="index" open="(" separator="," close=")"> #{item} </foreach>

方法3、sql注入,改为where id in (${clientIds})

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/qq_29766917/article/details/90167176

标签:[!--infotagslink--]

您可能感兴趣的文章: