一、Java 集合的創建與用法
在 Java 中,List
、HashSet
和數組是常用的集合類型,以下是它們的創建與基本操作:
1. List 列表
創建方式:
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)); // 可變列表
List<Integer> immutableList = List.of(1, 2, 3); // 不可變列表(Java 9+)
常用方法:
list.add(4); // 添加元素
list.remove(2); // 刪除索引為2的元素
list.get(0); // 獲取第一個元素
list.contains(3); // 判斷是否包含元素3
2. HashSet 集合
創建方式:
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3)); // 無序、不重復集合
常用方法:
set.add(4); // 添加元素(若存在則忽略)
set.remove(2); // 刪除元素2
set.contains(3); // 判斷是否包含元素3
3. Integer 數組
創建方式:
Integer[] array = {1, 2, 3}; // 直接初始化
Integer[] array2 = new Integer[3]; // 聲明長度為3的空數組
array2[0] = 1; array2[1] = 2; array2[2] = 3; // 賦值
遍歷方式:
for (int num : array) {System.out.println(num);
}
二、MyBatis 中集合參數的處理
MyBatis 的 <foreach>
標簽用于遍歷集合生成動態 SQL,但不同集合類型需配置不同的 collection
屬性。
1. 參數為 List
Mapper 接口方法:
List<Emp> findByIds(List<Integer> ids);
XML 配置:
<foreach collection="list" item="id" ...> <!-- 必須用 list -->
原因:
MyBatis 默認將 List
類型參數命名為 list
,因此 collection="list"
。
2. 參數為 Collection(如 HashSet)
Mapper 接口方法:
List<Emp> findByIds2(Set<Integer> ids); // 或 Collection<Integer> ids
XML 配置:
<foreach collection="collection" item="id" ...> <!-- 必須用 collection -->
原因:
MyBatis 將非 List
的 Collection
類型(如 Set
)統一命名為 collection
。
3. 參數為數組
Mapper 接口方法:
List<Emp> findByIds3(Integer[] ids);
XML 配置:
<foreach collection="array" item="id" ...> <!-- 必須用 array -->
原因:
MyBatis 將數組類型參數命名為 array
。
三、測試代碼解析
用戶提供的測試類 demo02.java
展示了不同集合參數的傳遞方式:
// 測試 List 參數
@Test
public void testFindByIds() {List<Integer> ids = Arrays.asList(1, 2, 3);mapper.findByIds(ids).forEach(System.out::println); // 調用 list 方法
}// 測試 HashSet 參數
@Test
public void testFindByIds2() {Set<Integer> ids = new HashSet<>(Arrays.asList(1, 2, 3));mapper.findByIds2(ids).forEach(System.out::println); // 調用 collection 方法
}// 測試數組參數
@Test
public void testFindByIds3() {Integer[] ids = {1, 2, 3};mapper.findByIds3(ids).forEach(System.out::println); // 調用 array 方法
}
四、常見問題與解決方案
1. 如何自定義集合參數名稱?
若想使用自定義名稱(如 ids
),需通過 @Param
注解顯式指定:
List<Emp> findByIds(@Param("ids") List<Integer> ids);
XML 中改為:
<foreach collection="ids" item="id" ...>
2. 混合參數如何處理?
當方法有多個參數時,需為集合參數添加 @Param
:
List<Emp> findByIdsAndName(@Param("ids") List<Integer> ids,@Param("name") String name
);
XML 中使用 ids
和 name
:
<if test="name != null"> AND name = #{name} </if>
<foreach collection="ids" item="id" ...>
3. 集合為空時的處理
為避免 SQL 語法錯誤,需在 <foreach>
外層添加判空條件:
<if test="ids != null and !ids.isEmpty()">id IN<foreach collection="list" item="id" open="(" separator="," close=")">#{id}</foreach>
</if>
五、總結
集合類型 | Java 創建方式 | MyBatis 的 collection 屬性 |
---|---|---|
List | Arrays.asList(1, 2, 3) | list |
HashSet | new HashSet<>(Arrays.asList(...)) | collection |
數組 | Integer[] ids = {1, 2, 3} | array |
關鍵點:
- MyBatis 默認對
List
、Collection
、數組使用固定名稱list
、collection
、array
。 - 使用
@Param
可自定義參數名稱,增強可讀性。 - 始終檢查集合是否為空,避免動態 SQL 拼接錯誤。
通過掌握這些規則,可以高效處理 MyBatis 中的集合參數,實現靈活的動態查詢。