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

这篇文章主要介绍了Mybatis 如何传入字符串参数,分割并遍历,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

 

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

如前台传入字符串参数 

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

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

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

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

如修改为:

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

程序报错。

正确写为如下

1
2

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遍历

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

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

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

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

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

原文链接:https://www.jb51.net/article/235376.htm

posted @ 2022-04-28 16:47  小陈子博客  阅读(2169)  评论(0编辑  收藏  举报