下面提供一个mybatis的foreach的用法,这里面有个属性是collection,这个属性的值怎么来确定呢??
<if test="pd.statusList != null and pd.statusList.size() > 0">
and addr.status in
<foreach collection="pd.statusList" separator="," open="(" close=")" item="item" index="index">
#{pd.statusList[${index}]}
</foreach>
</if>
首先这里需要分几种情况:
1>单参数,切参数是数组。collection取值array
2><span style="font-family: Arial, Helvetica, sans-serif;">单参数,切参数是list。collection取值list</span>
<span style="font-family:Arial, Helvetica, sans-serif;">3>如果参数传递过来是一个map,那么</span><span style="font-family: Arial, Helvetica, sans-serif;">collection的取值就是具体的参数的key。这个还有一点注意的就是:貌似如果参数进行两层封装,用#{item}</span><span style="font-family: Arial, Helvetica, sans-serif;">就取不到值了,取值就要使用上面的方式了。</span><span style="font-family: Arial, Helvetica, sans-serif;">
</span><span style="font-family:Arial, Helvetica, sans-serif;">
</span><div>
</div>
这里补充下批量插入:
<insert id="addIPAddr" parameterType="list" useGeneratedKeys="false">
<span style="white-space:pre"> </span> insert into devaddrinfo (deviceid,ippoolname,status,startip,endip,startfullip,endfullip,addnum)
<span style="white-space:pre"> </span> <foreach collection="list" item="item" index="index" separator="union all" >
<span style="white-space:pre"> </span> select '${item.deviceId}','${item.ippoolName}','${item.status}','${item.startIP}','${item.endIP}','${item.startFullIP}','${item.endFullIP}','${item.addnum}' from dual
<span style="white-space:pre"> </span> </foreach>
<span style="white-space:pre"> </span></insert>
大致的意思就是将list的数据union all 起来,用beigin end;包起来,这里面<span style="font-family: Arial, Helvetica, sans-serif;">useGeneratedKeys="false"这个属性默认要加上,但是我也没搞明白为什么要加上去</span>