当前位置: 首页 > news >正文

Java 集合与 MyBatis 动态 SQL 实战教程


一、Java 集合的创建与用法

在 Java 中,ListHashSet 和数组是常用的集合类型,以下是它们的创建与基本操作:

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 将非 ListCollection 类型(如 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 中使用 idsname

<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 属性
ListArrays.asList(1, 2, 3)list
HashSetnew HashSet<>(Arrays.asList(...))collection
数组Integer[] ids = {1, 2, 3}array

关键点

  • MyBatis 默认对 ListCollection、数组使用固定名称 listcollectionarray
  • 使用 @Param 可自定义参数名称,增强可读性。
  • 始终检查集合是否为空,避免动态 SQL 拼接错误。

通过掌握这些规则,可以高效处理 MyBatis 中的集合参数,实现灵活的动态查询。

http://www.xdnf.cn/news/427411.html

相关文章:

  • 普通项目与 FreeRTOS 项目的异同
  • 【NLP 72、Prompt、Agent、MCP、function calling】
  • 全景系统监控利器:Glances 使用介绍与实战指南
  • 【数据结构】双向链表
  • 开发与AI融合的Windsurf编辑器
  • 屏幕与触摸调试
  • Retrofit vs Feign: 介绍、对比及示例
  • 关于 javax.validation.constraints的详细说明
  • Visual Studio 项目 .gitignore 文件指南
  • 如何界定合法收集数据?
  • 【C++】【设计模式】生产者-消费者模型
  • EDR与XDR如何选择适合您的网络安全解决方案
  • 自我奖励语言模型:突破人类反馈瓶颈
  • WebGIS开发面试题:前端篇(六)
  • 【递归、搜索与回溯】专题一:递归(二)
  • electron 基础知识
  • 软考软件评测师——计算机组成与体系结构(分级存储架构)
  • 当三维地理信息遇上气象预警:电网安全如何实现“先知先觉”?
  • 项目中会出现的css样式
  • MQTT协议详解:物联网通信的轻量级解决方案
  • JMeter同步定时器 模拟多用户并发访问场景
  • Qt进阶开发:QTcpSocket的详解
  • Leetcode 3542. Minimum Operations to Convert All Elements to Zero
  • APISQL免费版安装教程(视频)
  • java刷题基础知识
  • 【Folium】使用离线地图
  • 我的MCP相关配置记录
  • Cursor 编辑器 的 高级使用技巧与创意玩法
  • JavaScript异步编程 Async/Await 使用详解:从原理到最佳实践
  • 基于RT-Thread的STM32F4开发第三讲——DAC