mybatis中使用where in查询时的注意事项
我使用的时候collection值为mapper的参数名
如:int deleteRoleByUserIds(@Param("userIds") String[] userIds);
1 2 3 4 5 6 7 | <delete id= "deleteRoleByUserIds" > delete from uc_user_role where user_id in <foreach item= "item" index= "index" collection= "userIds" open= "(" separator= "," close= ")" > #{item} </foreach> </delete> |
====================================================
1. 当查询的参数只有一个时
findByIds(List<Long> ids)
1.a 如果参数的类型是List, 则在使用时,collection属性要必须指定为 list
<select id="findByIdsMap" resultMap="BaseResultMap"> Select <include refid="Base_Column_List" /> from jria where ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
findByIds(Long[] ids)
1.b 如果参数的类型是Array,则在使用时,collection属性要必须指定为 array
<select id="findByIdsMap" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from jria where ID in <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> </select>
2. 当查询的参数有多个时,例如 findByIds(String name, Long[] ids)
这种情况需要特别注意,在传参数时,一定要改用Map方式, 这样在collection属性可以指定名称
下面是一个示例
Map<String, Object> params = new HashMap<String, Object>(2); params.put("name", name); params.put("ids", ids); mapper.findByIdsMap(params); <select id="findByIdsMap" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from jria where ID in <foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> #{item} </foreach> </select>
完整的示例如下:
例如有一个查询功能,Mapper接口文件定义如下方法:
List<Jria> findByIds(Long... ids);
使用 in 查询的sql拼装方法如下:
<select id="findbyIds" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from jria where ID in <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> </select>
分类:
数据库
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2016-08-23 Linux命令行–理解Linux文件权限(转)
2016-08-23 简述Mesos API–files
2014-08-23 POJ1201 Intervals
2014-08-23 POJ3159 Candies
2014-08-23 POJ2983 Is the Information Reliable?