mybatis处理集合、数组参数使用in查询等语句的两种方法

对于mybatis的参数类型是集合数组的时候进行查询。顺便回忆一下。有两种处理方式。

第一种:参数list

使用mybatis的标签

SELECT  * FROM  TABLE_NAME AS a WHERE

a.id not in #{extraIds}
<foreach collection="extraIds" item="extraId" index="i" open="(" separator="," close=")">
        #{extraId}

</foreach>

参数讲解的:

collection:需要循环的集合

item:每次循环的参数名字

index:索引(0开始)

separator:分隔符

open:整个循环开始的分隔符

close:整个循环结束的分隔符

第二种:参数string的数组

需要处理参数形成extraIds=('1','2','3')这种类型,需要拼接字符 ''

注意在mybatis中使用的是${},不能使用#{}否则报错

SELECT  * FROM  TABLE_NAME AS a WHERE

a.id not in ${extraIds}

一小段示类代码:

String extraIds = "1,2,3,4,5";

 String[] extraIdArray = extraIds.split(",");
            extIds = "";
            for (String extraId : extraIdArray) {
                if (extraId != null && !"".equals(extraId)) {
                    extraIds += ",'" + extraId + "'";
                }

            }

 extraIds   =    "(" + extraIds.substring(1) + ")"

拼接后:('1','2','3','4','5'


猜你喜欢

转载自blog.csdn.net/weixin_38391672/article/details/80701504