foreach

 

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。

 

foreach元素的属性主要有 item,index,collection,open,separator,close。

略解:

item:表示集合中每一个元素进行迭代时的别名,【表示集合的名字】

index:指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,

open:表示该语句以什么开始,

separator:表示在每次进行迭代之间以什么符号作为分隔 符,

close:表示以什么结束。

详解:

描述

item:循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。

具体说明:在list和数组中是其中的对象,在map中是value。

该参数为必选。

collection:要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键。

当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:

如果User有属性List ids。入参是User对象,那么这个collection = "ids"

如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

上面只是举例,具体collection等于什么,就看你想对那个元素做循环。

该参数为必选

separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。

open:foreach代码的开始符号,一般设置为“(“和close=")"合用。常用在in(),values()时。该参数可选。

close:foreach代码的关闭符号,一般设置为“)“和open="("合用。常用在in(),values()时。该参数可选。

index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

 

 

(1)List<T>集合

①在接口中

List<UserInfo> selectUserInfoByForEachList(List<String> sl);  

②.xml文件中

1. <select id="selectUserInfoByForEachList" resultMap="UserInfoResult">  
2.         select * from userinfo  
3.         <if test="list!=null">  
4.             where userid in  
5.             <foreach item="item" collection="list" index="index" open="("  
6.                 separator="," close=")">  
7.                 #{item}  
8.             </foreach>  
9.         </if>  
10.     </select>

注意:这样写的原因是因为这是一个列表,collection:里面直接写list 就可以,不需要将名字穿过来

(2)Arrary[] 集合

①在接口中

List<UserInfo> selectUserInfoByForEachArray(String[] sa);

②.xml文件中

1. <select id="selectUserInfoByForEachArray" resultMap="UserInfoResult">  
2.         select * from userinfo  
3.         <if test="array!=null">  
4.             where userid in  
5.             <foreach item="item" collection="array" index="index" open="("  
6.                 separator="," close=")">  
7.                 #{item}  
8.             </foreach>  
9.         </if>  
10.     </select>

注意:这样写的原因是因为这是一个数组,collection:里面直接写array 就可以,不需要将名字穿过来

 

(3)Map集合

①在接口中

List<UserInfo> selectUserInfoByForEach(Map<String,Object> map);

②在.xml文件中

1. <select id="selectUserInfoByForEach" parameterType="Map"  
2.         resultMap="UserInfoResult">  
3.         select * from userinfo  
4.         <if test="userids!=null">  
5.             where userid in  
6.             <foreach item="ParamsId" collection="userids" index="index"  
7.                 open="(" separator="," close=")">  
8.                 #{ParamsId}  
9.             </foreach>  
10.         </if>  
11.     </select>

【解释】

a.与上面类似:这里的if标签能够判断出map中否包含userids这个key,其对应的value可以任意。但是没有判断出value中的内容是否为空。即,当value中有内容时或者key不存在时,该SQL语句能够正常执行,但是如果value为空的话,if判断的结果为真,但foreach执行0次。这种情况下,Mybatis会组装出1条错误的sql语句。换句话说这里if是多余的。

b.这里collection属性配置为map中list对应的key的值,而不是value或者”list“

c.各位看官请注意这里的#{ParamsId}是与属性item中的ParamsId对应的