邢台 建网站高端文化网站
2026/1/15 11:42:02 网站建设 项目流程
邢台 建网站,高端文化网站,北京市城乡建设部网站首页,wordpress媒体库是哪个文件夹在这条 MyBatis 动态 SQL 中#xff0c;where 11 是动态拼接 WHERE 条件的经典技巧#xff0c;核心作用是#xff1a;解决 “第一个动态条件前是否需要加 AND” 的问题#xff0c;让条件拼接逻辑更简洁、无歧义。一、先看核心问题#xff1a;没有 11 会怎样#xff1f;假…在这条 MyBatis 动态 SQL 中where 11是动态拼接 WHERE 条件的经典技巧核心作用是解决 “第一个动态条件前是否需要加 AND” 的问题让条件拼接逻辑更简洁、无歧义。一、先看核心问题没有11会怎样假设去掉where 11SQL 会变成where if testquery.shopIdList ! null and query.shopIdList.size()0 and a.shopId in (...) /if if testquery.shopId ! null and query.shopId ! and a.shopId#{query.shopId} /if ...如果第一个动态条件不满足比如shopIdList为 null最终拼接的 SQL 会是select ... from dws_shop_itemcate_sum a where and a.shopIdxxxwhere后直接跟and触发SQL 语法错误BadSqlGrammarException。二、where 11的核心作用11是一个恒成立的条件不会过滤任何数据但它能占住where后的第一个位置所有动态条件都可以统一以and开头无需判断 “是不是第一个条件”不影响查询结果11永远为真不会过滤任何数据最终的查询结果只由后续的动态条件决定简化逻辑开发时不用逐个判断 “当前条件是不是第一个”所有动态条件都按and 条件写即可降低出错概率。三、代码执行示例更直观场景 1仅传shopIdList[9001,9002]最终拼接的 SQLselect ... from dws_shop_itemcate_sum a where 11 and a.shopId in (9001,9002)场景 2仅传shopId9003beginTime2025-01-01最终拼接的 SQLselect ... from dws_shop_itemcate_sum a where 11 and a.shopId9003 and a.reportDate2025-01-01场景 3不传任何动态条件最终拼接的 SQLselect ... from dws_shop_itemcate_sum a where 11等价于select ... from dws_shop_itemcate_sum a查询全表四、替代方案MyBatis 更优雅的写法MyBatis 提供了where标签可以替代11自动处理多余的and/orselect idsumNumberCardDataByShop resultTypeStNumberCardDataBO select include refidnumberCard_queryColumn/ from dws_shop_itemcate_sum a where !-- 替代 where 11 -- if testquery.shopIdList ! null and query.shopIdList.size()0 a.shopId in !-- 去掉 and -- foreach collectionquery.shopIdList itemshopId indexindex open( close) separator, #{shopId} /foreach /if if testquery.shopId ! null and query.shopId ! and a.shopId#{query.shopId} !-- 保留 and -- /if if testquery.beginTime ! null and query.beginTime ! ![CDATA[ and a.reportDate#{query.beginTime} ]] /if if testquery.endTime ! null and query.endTime ! ![CDATA[ and a.reportDate#{query.endTime}]] /if /where /selectwhere标签的优势若有动态条件满足自动添加where并去掉第一个条件前的and/or若没有动态条件满足不生成where子句避免where 11全表查询比11更优雅是 MyBatis 推荐的写法。五、总结where 11的本质用恒真条件占位让所有动态条件统一以and开头避免语法错误优缺点优点简单易懂新手友好缺点若所有动态条件都不满足会生成where 11导致全表查询可能性能低

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询