目录
3.1 collection属性值为List(Array等同):
1.foreach元素的属性
-
collection: foreach的对象,作为入参,对象为list、array时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“name”)注解来设置自定义collection属性值,设置name后,list、array会失效;
-
item: 集合元素迭代时的别名称,该参数为必选项,如果遍历的对象是map,则item为val;
-
index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;
-
open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;
-
separator: 元素之间的分隔符,类比在IN()的时候,separator=",",最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;
-
close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;
2.collection属性值的三种情况
-
如果传入的参数类型为list时: collection的默认属性值为list,同样可以使用@Param注解自定义name;
-
如果传入的参数类型为array时: collection的默认属性值为array,同样可以使用@Param注解自定义name;
-
如果传入的参数类型为Map时: collection的属性值可为三种情况:(1.遍历map.keys;2.遍历map.values;3.遍历map.entrySet()),稍后会在代码中示例;
3.代码示例
3.1 collection属性值为List(Array等同):
@select(
"<script> " +
"SELECT *
" FROM user_info " +
" WHERE " +
" <if test="userName!= null and userName.size() >0"> " +
" USERNAME IN " +
" <foreach collection='userNames' item='value' separator=',' open='(' close=')'>" +
" #{value} " +
" </foreach>" +
" </if>" +
"</script>"
)
list<userInfo> getUserInfo(@param("userNames") list<String> userNames)
#separator不仅仅使用,使用or或者and,open不仅仅只是使用(而是and (
@select(
"<script> " +
"SELECT CONFIGID AS configId count(CONFIGID) as count*
" FROM user_info " +
" WHERE " +
" devGroupId = #{devGroupId}" +
" <foreach collection='viewRange' item='item' separator='or' open=' and (' close=')'>" +
" ORGNODEPATH like CONCAR('%','<![CDATA[#{item}]]>','%') " +
" </foreach>" +
"</script>"
)
list<Map<String,Long>> queryConfigAndCount(@param("devGroupId") long devGroupId, @param("viewRange") set<Long> viewRange)
3.2 collection属性值类型为Map:
@select(
"<script> " +
"SELECT *
" FROM user_info " +
" WHERE " +
" <if test="userName!= null and userName.size() >0"> " +
" (USERNAME,AGE) IN " +
" <foreach collection='user.entrySet()' index='key' item='value' separator=',' open='(' close=')'>" +
" #{key},#{value} " +
" </foreach>" +
" </if>" +
"</script>"
)
List<UserList> getUserInfo(@Param("user") Map<String,String> user);
@select(
"<script> " +
"SELECT *
" FROM user_info " +
" WHERE " +
" <if test="userName!= null and userName.size() >0"> " +
" USERNAME IN " +
" <foreach collection='user.keys' item='key' separator=',' open='(' close=')'>" +
" #{key} " +
" </foreach>" +
" </if>" +
"</script>"
)
List<UserList> getUserInfo(@Param("user") Map<String,String> user);
@select(
"<script> " +
"SELECT *
" FROM user_info " +
" WHERE " +
" <if test="userName!= null and userName.size() >0"> " +
" USERNAME IN " +
" <foreach collection='user.values' item='value' separator=',' open='(' close=')'>" +
" #{value} " +
" </foreach>" +
" </if>" +
"</script>"
)
List<UserList> getUserInfo(@Param("user") Map<String,String> user);