MyBatis傳入多個引數,傳入陣列和列表資料的處理
阿新 • • 發佈:2019-02-07
java定義:
List<RoleEx> selectByRoleIdList(@Param("roles")String[] roles);
List<RoleEx> selectByRoleIdList1(@Param("roles")List<Integer> roles);
xml定義:
<select id="selectByRoleIdList" resultMap="NamedResultMap" > SELECT .... FROM tm04_role a <if test="roles != null"> where a.role_id in( <foreach collection="roles" item="roleId" index="index" separator="," > #{roleId,jdbcType=INTEGER} </foreach> ) </if> order by a.role_name </select> <select id="selectByRoleIdList1" resultMap="NamedResultMap" > SELECT ... FROM tm04_role a <if test="roles != null"> where a.role_id in( <foreach collection="roles" item="roleId" index="index" separator="," > #{roleId,jdbcType=INTEGER} </foreach> ) </if> order by a.role_name </select>
測試程式碼:
String[] roles1 = {"1","2"}; List<RoleEx> list3 = mapper.selectByRoleIdList(roles1); System.out.println(objMapper.writeValueAsString(list3)); List<Integer> roles2 = new ArrayList<Integer>(); roles2.add(1); roles2.add(2); List<RoleEx> list4 = mapper.selectByRoleIdList1(roles2); System.out.println(objMapper.writeValueAsString(list4));
看看標籤定義:
在mybatis的mapper配置檔案中,可以利用<foreach>標籤實現sql條件的迴圈,可完成類似批量的sql mybatis接受的引數分為:(1)基本型別(2)物件(3)List(4)陣列(5)Map 無論傳哪種引數給mybatis,他都會將引數放在一個Map中: 如果傳入基本型別:變數名作為key,變數值作為value 此時生成的map只有一個元素。 如果傳入物件: 物件的屬性名作為key,屬性值作為value, 如果傳入List: "list"作為key,這個List是value (這類引數可以迭代,利用<foreach>標籤實現迴圈) 如果傳入陣列: "array"作為key,陣列作為value(同上) 如果傳入Map: 鍵值不變。 <foreach>標籤的用法: 六個引數: collection:要迴圈的集合 index:迴圈索引(不知道啥用。。) item:集合中的一個元素(item和collection,按foreach迴圈理解) open:以什麼開始 close:以什麼結束 separator:迴圈內容之間以什麼分隔