mybatis中传递list集合

今天写后端时候想在xml中sql用in,但是又不知道该怎么写,因为传递进来的集合不确定个数,后来在大佬的指点下找到了方法用foreach,这边查阅一些资料做一下笔记:

foreach常用属性:
collection:需做foreach的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“paramName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;

item: 集合元素迭代时的别名称,该参数为必选项

index:map中代指key,其它时用于表示在迭代过程中,每次迭代到的位置

separator:元素间的分隔符

open:遍历集合开始时使用

close:遍历集合结束时使用

 

这种是常规list,将collection中属性值设置为list:

复制代码
DAO 层:
Long selectCustomerCountList( List customerIdList);
 
XML文件:
<select id="selectCustomerCountList" parameterType="java.util.List" resultType="java.lang.Long">
    select count(1) from np_customer_info where id in
    <foreach item="item" collection="list" separator="," open="(" close=")" index="">
        #{item, jdbcType=INTEGER}   
    </foreach>
</select>
    
======================
注意:此时collection强制指定为list且不可改变
复制代码

这种是使用注解@Params指定入参list名称:

复制代码
DAO层:
Long selectCustomerCountList(@Param("customerIdList") List customerIdList);
 
XML文件:
<select id="selectCustomerCountList" parameterType="java.util.List" resultType="java.lang.Long">
    select count(1) from np_customer_info where id in
    <foreach item="item" collection="customerIdList" separator="," open="(" close=")" index="">  
        #{item, jdbcType=INTEGER}   
    </foreach>
</select>
 
======================
注意: 此时的DAO层参数名可以 @Param("customerIdList") 与 collection的属性值一致
复制代码

目前只用到这些,后续再进一步用到再做更新

原文链接:https://blog.csdn.net/jushisi/article/details/106674079

 

posted @   浮笙芸芸  阅读(894)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示