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

浙公网安备 33010602011771号