在 Java 中,List
、HashSet
和数组是常用的集合类型,以下是它们的创建与基本操作:
创建方式:
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
创建方式:
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3)); // 无序、不重复集合
常用方法:
set.add(4); // 添加元素(若存在则忽略)
set.remove(2); // 删除元素2
set.contains(3); // 判断是否包含元素3
创建方式:
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 的
标签用于遍历集合生成动态 SQL,但不同集合类型需配置不同的 collection
属性。
Mapper 接口方法:
List<Emp> findByIds(List<Integer> ids);
XML 配置:
<foreach collection="list" item="id" ...>
原因:
MyBatis 默认将 List
类型参数命名为 list
,因此 collection="list"
。
Mapper 接口方法:
List<Emp> findByIds2(Set<Integer> ids); // 或 Collection ids
XML 配置:
<foreach collection="collection" item="id" ...>
原因:
MyBatis 将非 List
的 Collection
类型(如 Set
)统一命名为 collection
。
Mapper 接口方法:
List<Emp> findByIds3(Integer[] ids);
XML 配置:
<foreach collection="array" item="id" ...>
原因:
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 方法
}
若想使用自定义名称(如 ids
),需通过 @Param
注解显式指定:
List<Emp> findByIds(@Param("ids") List<Integer> ids);
XML 中改为:
<foreach collection="ids" item="id" ...>
当方法有多个参数时,需为集合参数添加 @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" ...>
为避免 SQL 语法错误,需在
外层添加判空条件:
<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 |
关键点:
List
、Collection
、数组使用固定名称 list
、collection
、array
。@Param
可自定义参数名称,增强可读性。通过掌握这些规则,可以高效处理 MyBatis 中的集合参数,实现灵活的动态查询。