MyBatis中foreach循環的用法

1、在瞭解foreach以前,先了解一下mybatis傳入參數及parameterType

一、咱們在Dao層向對應的mapper.xml文件傳遞參數時,能夠傳遞的參數有:java

  ①、基本數據類型(如int/Integer、long/Long、float等)sql

  ②、簡單引用數據類型(如String、User實體類對象等)數據庫

  ③、集合數據類型(如List、Map等)數組

  咱們在parameterType屬性獲取參數類型時,只須要與傳入的參數類型相同便可,如:mybatis

①基本數據類型:Java代碼:app

1 User findById(Integer id);

①基本數據類型:mapper.xml代碼:spa

1 <select id="findById" parameterType="int" resultType="com.demo.entity.User">
2         SELECT * FROM `user` where id=#{id};
3 </select>

②簡單引用類型:Java代碼:code

1 void addUser(User user);

②簡單引用類型:mapper.xml代碼:xml

1 <insert id="addUser" parameterType="com.demo.entity.User">
2         insert into `user` values (null,#{userName},#{userAge})
3 </insert>

③集合數據類型(List):Java代碼:對象

1 List<User> findUserListByIdList(List<Integer> idList);

③集合數據類型(List):mapper.xml代碼:

1 <select id="findUserListByIdList" parameterType="List" resultType="User">  
2     select * from `user `
3     <where>  
4         user.ID in   
5         <foreach collection="idList" index="index" item="value" open="(" close=")" separator=","> #{value} </foreach>   
6     </where>  
7 </select>  

 2、foreach屬性——collection、index、item、open、close、separator

屬性 描述
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等於什麼,就看你想對那個元素作循環。
該參數爲必選。

index 在list和數組中,index是元素的序號,在map中,index是元素的key,該參數可選。
item 循環體中的具體對象。支持屬性的點路徑訪問,如item.age,item.info.details。
具體說明:在list和數組中是其中的對象,在map中是value。
該參數爲必選。
open foreach代碼的開始符號,通常是(和close=")"合用。經常使用在in(),values()時。該參數可選。
close foreach代碼的關閉符號,通常是)和open="("合用。經常使用在in(),values()時。該參數可選。
separator 元素之間的分隔符,例如在in()的時候,separator=","會自動在元素中間用「,「隔開,避免手動輸入逗號致使sql錯誤,如in(1,2,)這樣。該參數可選。

3、foreach簡單使用:

(一)集合數據類型:Map<String, Object>

 1 // 初始化一個Map數據
 2 Map<String, Object> dataMap = new HashMap<String, Object>();
 3     dataMap.put("id", "0001");
 4     dataMap.put("name", "Tom");
 5     dataMap.put("age", "12");
 6 // 將dataMap傳遞到Dao層
 7 public void addUser(@Param("map") Map<String, Object> map);
 8 // DaoMapper.xml   mapper文件
 9 /* 這段添加語句的意思是:根據map提供的字段,向數據庫user表中,添加數據(只添加指定字段的數據);注意區分mybatis中「$」與「#」的用法 */
10 <insert id="addUser" parameterType="Map">
11     INSERT INTO `user`
12     <foreach collection="map" index="key" item="value" open="("
13         close=")" separator=",">
14  ${key}
15     </foreach>
16     VALUES
17     <foreach collection="map" index="key" item="value" open="("
18         close=")" separator=",">
19  #{value}
20     </foreach>
21 </insert>

(二)集合數據類型:List<Map<String, Object>> (list集合中存的是map)

 1 // 初始化一個數據
 2 Map<String, Object> dataMap1 = new HashMap<String, Object>();
 3 Map<String, Object> dataMap2 = new HashMap<String, Object>();
 4 List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
 5     dataMap1.put("name", "Tom");
 6     dataMap1.put("age", "13");
 7     dataList.add(dataMap1);
 8     dataMap2.put("name", "Jack");
 9     dataMap2.put("age", "18");
10     dataList.add(dataMap2);
11 // 將dataList傳遞到Dao層
12 public void addUser(List<Map<String, Object>> list);
13 // DaoMapper.xml
14 /* 批量向數據庫中添加數據 */
15 <insert id="addUser" parameterType="List">
16     INSERT INTO `user`(name, age) VALUES
17     <foreach collection="list" index="index" item="item" separator=",">
18         <foreach collection="item" index="key" item="value" open="(" close=")" separator=",">
19             #{value}
20         </foreach>
21     </foreach>
22 <insert>

(三) 集合數據類型:Map<String,Object>(map集合中存的數據有:String, List(List裏面存的是Map);)

 1 // 初始化數據
 2 // lineColumn 用來存須要添加的字段
 3     String lineColumn = "";
 4 // paramsMap 用來打包整個數據,並將數據傳遞到Dao層
 5     Map<String, Object> paramsMap = new HashMap<String, Object>();
 6 // 建立兩個map,用來存對應的字段和值,一個map就是一個新用戶
 7     Map<String, Object> dataMap1 = new HashMap<String, Object>();
 8     Map<String, Object> dataMap2 = new HashMap<String, Object>();
 9 // 建立一個list,以list來存用戶的map集合
10     List<Map<String, Object>> linList = new ArrayList<Map<String, Object>>();
11         dataMap1.put("name", "Tom");
12         dataMap1.put("age", "12");
13         linList.add(dataMap1);
14         dataMap2.put("name", "Jack");
15         dataMap2.put("age", "18");
16         linList.add(dataMap2);
17     for(String key : dataMap1.keySet()){
18         lineColumn += key + ",";
19     }
20     lineColumn = lineColumn.substring(0,lineColumn.lingth() - 1);
21     paramsMap.put("lineColumn", lineColumn);
22     paramsMap.put("table", "user");
23     paramsMap.put("lineList", lineList);
24 // 將paramsMap傳遞到Dao層
25 public void addUser(Map<String, Object> map);
26 // DaoMapper.xml; 根據map中傳遞的 表名, 字段名, 字段對應的數據 進行批量添加
27 /* 在Dao層傳入的map集合作數據中,若是隻須要拿map集合中某一個指定的單條數據時,在mapper.xml中能夠 以 ${key} 便可拿到數據 */
28 <insert id="addUser" parameterType="Map">
29     INSERT INTO `${table}` (${lineColumn}) VALUES
30     <foreach collection="lineList" index="index" item="item" separator=",">
31         <foreach collection="item" index="key" item="value" open="(" close=")" separator=",">
32             #{value}
33         </foreach>
34     </foreach>
35 </insert>

(四)數據集合類型:Map(根據集合中value是否爲null來選擇性的向數據庫添加數據)

 1 // 初始化一個數據
 2 Map<String, Object> dataMap = new HashMap<String, Object>();
 3     dataMap.put("id", "001");
 4     dataMap.put("name","Tom");
 5     dataMap.put("age", null);
 6 // 傳遞到Dao層
 7 public void addUser(@Param("map") Map<String, Object> map);
 8 // DaoMapper.xml
 9 /* 根據參數是否爲null來選擇性的向數據庫添加數據 */
10 <insert id="addUser" parameterType="Map">
11     INSERT INTO `user`
12     <foreach collection="map" index="key" item="value" open="(" close=")" separator=",">
13         <if test="value != null and value != '' ">
14             ${key}
15         </if>
16     </foreach>
17     VALUES
18     <foreach collection="map" index="key" item="value" open="(" close=")" separator=",">
19         <if test="value != null and value != '' ">
20             #{value}
21         </if>
22     </foreach>
23 </insert>

*在mapper.xml中,使用"if"或者"where"標籤小小的注意事項:

  在使用if或者where標籤時,如<if test=" id != null ">(當你傳遞參數是一個單類型時( user findById(Integer id); )),有可能報一個異常「There is no getter for property named ‘xxx’ in 'class java.lang.xxx';

  此時解決辦法:

  ①將<if test=" id != null "> 中的「id」更改成「_parameter」;

  ②在接口方法中(user findById (Integer id);)添加@Param("xxx")註解,如user findById (@Param("id") Integer id)

相關文章
相關標籤/搜索