Java 集合与 MyBatis 动态 SQL 实战教程
一、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 中的集合参数,实现灵活的动态查询。