Mybatis 中的 List Array Map 的foreach 、in

原文来源:http://blog.csdn.net/qh_java/article/details/50754271java

 

在mybatis 的配置文件中咱们常常会用到集合 数组以及map的批量查询,这样咱们就会常常用到 foreach 了,首先来看看foreach的属性:sql

这张图写的很全,很好就那个了你知道的……数组

知道了这些属性咱们就来看看小demo:mybatis

一、List<Integer>  IntList   、 List<String> strList   集合中存的是基本类型的this

 

[java]  view plain  copy
 
  1. <select id="dynamicForeachTest" parameterType="java.util.List"  resultMap="Users">  
  2.     select id,name from t_blog where id in  
  3.     <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
  4.         #{item}  
  5.     </foreach>  
  6. </select>  
其中的传的参数是List集合因此collection 的值直接使用了list 来代替而index 就是这个集合遍历的索引值,item 就是list当前索引位置的值 open 和close 成对出现,就是开始和结束的符号,而separator 就是分隔符。

 

二、List<Obect>  objList 、List<Users>  userList 引用类型的数据spa

 

[java]  view plain  copy
 
  1. package soufun.com;  
  2. /** 
  3.  *@author WHD 
  4.  *data 2016年2月27日 
  5.  */  
  6. public class Users {  
  7. private int id;  
  8. private String name;  
  9. public int getId() {  
  10.     return id;  
  11. }  
  12. public void setId(int id) {  
  13.     this.id = id;  
  14. }  
  15. public String getName() {  
  16.     return name;  
  17. }  
  18. public void setName(String name) {  
  19.     this.name = name;  
  20. }  
  21.   
  22. }  
以这个类为例来看看:

 

 

[java]  view plain  copy
 
  1. <select id="dynamicForeachTest" parameterType="java.util.List" resultMap="Users">  
  2.     select id,name from t_blog where id in  
  3.     <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
  4.         #{item.id}  
  5.     </foreach>  
  6. </select>  

 

循环插入.net

 

[java]  view plain  copy
 
  1. insert into t_blog(id,name) values  
  2. <foreach collection="list" item="item" index="index" separator=",">    
  3.     (#{item.id},#{item.name})  
  4. </foreach>  

 

 

到这里都结束了,但还有个小事说一下,那就是in 的那个遍历,通常咱们都是使用foreach 来组装 的可是有看到这样写的:orm

String  name ="'w1','w2','w3','w4'";blog

 

[java]  view plain  copy
 
  1. <select id="getByMap" resultMap="Users">  
  2.  SELECT *  FROM t_blog  where  name in (${name})     
  3.  </select>  
这就是本身组装了 in的字符串,而没有使用mybatis的foreach 来组装实际上是同样的。

三、Map的使用,若是用Map作参数,则处理的方式和传一个基本变量同样直接引用就ok索引

 

[java]  view plain  copy
 
  1. <select id="selectjdnotconfirmorder" parameterType="java.util.Map" resultMap="result">  
  2.         select bzOrderId,jdOrderId,name,mobile,success from jdorderinfo where jdIsOrder = ${notSubmit} and success =${success}  
  3.     </select>  
这个sql中参数类型是Map,map参数以下:

 

 

[java]  view plain  copy
 
  1. Map<String,Integer> hashMap= new HashMap<String,Integer>();  
  2.         hashMap.put("notSubmit", notSubmit);  
  3.         hashMap.put("success", state);  
四、mybatis中的# 和$ 的区别,#的变量是带单引号的而$是不带单引号的,就好比上面的notSubmit 和success两个变量是int型的因此不用#而是$,由于是数字而不是字符。