foreach主要用在SQL中的IN中,利用foreach可以在SQL语句中对集合进行迭代。。。。
主要属性有,item、index、collection、open、separation、close,其中item表示对集合中每个元素进行迭代时的别名,index表示集合迭代到的位置,open表示语句以什么开始,close表示语句以什么结束,separation则表示以什么符号分隔每个元素。
其中collection最难理解。。。若我们迭代的对象本身是一个List,那么就写 collection="list",若迭代的对象为array数组,那么写collection="array",还有一种情况是,有时我们将参数用Map进行封装,那么如果我们要迭代Map中的某个元素,那么我们只要找到这个值对应的key即可,假如Map如下:
1.List<Long> ids = new ArrayList<Long>();
ids.add(1);
ids.add(2);
ids.add(3);
2. int[] userIds = new int[] {4,5,6};
3.Map<String,Object> map = new HashMap<String,Object>();
map.put("ids",ids);
map.put("userIds",userIds)
假设数据库表为user,有字段userid、username、age,对应如上三种情况,我们在MyBatis中的写的foreach语句分别如下所示:
1.select * from user where userid in
<foreach collection="list",index="index",item="id",open="(",separation=",",close=")" >
${id}
</foreach>
那么,我们对ids进行迭代后得到的SQL为 select * from user where userid in (1,2,3)
2.select * from user where userid in
<foreach collection="array",index="index",item="id",open="(",separation=",",close=")" >
${id}
</foreach>
那么,我们对userIds进行迭代后得到的SQL为 select * from user where userid in (4,5,6)
3.select * from user where userid in
<foreach collection="ids",index="index",item="id",open="(",separation=",",close=")" >
${id}
</foreach>
此种情况是传入的参数为Map,迭代后的SQL为select * from user where userid in (1,2,3)
----------------------
追加 今天测试的时候发现 当我们的集合为空的时候 会报SQL错误 所以在用的时候还要注意集合为空的时候的处理 要么就自己保证不会传入空值 要么就自己考虑如果集合为空 如何确保自己的SQL能顺利通过。
----------------------
另外,对于ORACLE数据库,in是用限制数量的,好像是1000,所以若要查询的in中个数大于1000的,要分开查询,每1000查询一次数据库,不然程序将会报错。