新闻详情

新闻详情

首页 / 资讯中心 / 详情

开发踩坑记:MyBatis selectKey、空 SQL

发布时间:2026/11/19 5:10:28来源:尧图网络
开发踩坑记:MyBatis selectKey、空 SQL
开发踩坑记MyBatis selectKey、空 SQL最近整理了一些开发过程中遇到的典型问题涉及 MyBatis 动态 SQL、selectKey使用、MySQL 时间字段。本文把这些零散笔记整理成一篇博客方便后续查阅也希望能帮到遇到类似问题的同学。一、MyBatis selectKey 报错No setter found for the keyProperty ‘count’在使用 MyBatis 的selectKey时可能会遇到这样的错误No setter found for the keyProperty count示例代码selectKeykeyPropertycountresultTypeintorderBEFOREselect count(*) from company_sign_type_relation where sign_id #{signId}/selectKey原因selectKey会把查询结果放到keyProperty指定的属性中。这里指定了keyPropertycount但传入的 PO 对象中没有count字段或者没有对应的 setter 方法于是 MyBatis 反射注入失败。解决在 PO 对象中添加count属性并提供 getter / setterprivateIntegercount;publicIntegergetCount(){returncount;}publicvoidsetCount(Integercount){this.countcount;}selectKey 属性说明keyProperty对应 PO 对象中的字段名。orderBEFORE/AFTER表示selectKey中的 SQL 在主 SQL 执行之前还是之后执行。resultTypekeyProperty对应字段的类型。二、MyBatis 动态 SQL 报错Query was empty另一个常见错误是MySQLSyntaxErrorException: Query was empty示例insertidsaveBatchByUniqueKeyselectKeykeyPropertycountresultTypeintorderBEFOREselect count(*) from company_sign_type_relation where sign_id #{signId}/selectKeyiftestcount0insert into company_sign_type_relation ( company_type_id, company_id, sign_id ) values ( #{companyTypeId}, #{companyId}, #{signId} )/if/insert原因当count 0不成立时if里面的 SQL 不会拼接。最终 MyBatis 没有生成任何可执行 SQL于是向数据库发送了空语句导致Query was empty。解决方式方式一把条件判断放到 Service 层在 Service 层先查询是否存在再决定是否调用 insert。这样 SQL 层只负责单一职责逻辑更清晰。方式二在 SQL 中增加兜底分支例如insertidsaveBatchByUniqueKeyselectKeykeyPropertycountresultTypeintorderBEFOREselect count(*) from company_sign_type_relation where sign_id #{signId}/selectKeyiftestcount0insert into company_sign_type_relation ( company_type_id, company_id, sign_id ) values ( #{companyTypeId}, #{companyId}, #{signId} )/ififtestcount 0select NOW();/if/insert这种方式可以避免空 SQL但实际开发中更推荐把业务判断放到 Service 层或者直接使用数据库的原子 upsert。三、saveOrUpdate 的 MyBatis 实现与并发风险类似下面这种“先 count再 insert 或 update”的写法很常见insertidsaveOrUpdateByEquipPassTeamselectKeykeyPropertycountresultTypeintorderBEFOREselect count(*) from iot_attendance_record_info where device_no #{deviceNo} and pass_time #{passTime}/selectKeyiftestcount0insert into iot_attendance_record_info ( device_no, brand_id, direction, pass_time, pass_date, person_id, person_primary_id, person_name, id_number, phone_number, group_leader_phone, is_group_leader, sex, age, sign_id, sign_name, company_id, company_name, company_type_id, company_type_name, type_work_id, type_work_name, team_id, team_name, group_leader_id, group_leader_name, boss_id, boss_name, boss_phone, create_time, update_time, is_deleted, person_oss_url, lj_person_id ) values ( #{deviceNo}, #{brandId}, #{direction}, #{passTime}, #{passDate}, #{personId}, #{personPrimaryId}, #{personName}, #{idNumber}, #{phoneNumber}, #{groupLeaderPhone}, #{isGroupLeader}, #{sex}, #{age}, #{signId}, #{signName}, #{companyId}, #{companyName}, #{companyTypeId}, #{companyTypeName}, #{typeWorkId}, #{typeWorkName}, #{teamId}, #{teamName}, #{groupLeaderId}, #{groupLeaderName}, #{bossId}, #{bossName}, #{bossPhone}, #{createTime}, #{updateTime}, #{isDeleted}, #{personOssUrl}, #{ljPersonId} )/ififtestcount 0update iot_attendance_record_infosetdevice_no #{deviceNo}, brand_id #{brandId}, direction #{direction}, pass_time #{passTime}, pass_date #{passDate}, person_id #{personId}, person_primary_id #{personPrimaryId}, person_name #{personName}, id_number #{idNumber}, phone_number #{phoneNumber}, group_leader_phone #{groupLeaderPhone}, is_group_leader #{isGroupLeader}, sex #{sex}, age #{age}, sign_id #{signId}, sign_name #{signName}, company_id #{companyId}, company_name #{companyName}, company_type_id #{companyTypeId}, company_type_name #{companyTypeName}, type_work_id #{typeWorkId}, type_work_name #{typeWorkName}, team_id #{teamId}, team_name #{teamName}, group_leader_id #{groupLeaderId}, group_leader_name #{groupLeaderName}, boss_id #{bossId}, boss_name #{bossName}, boss_phone #{bossPhone}, create_time #{createTime}, update_time #{updateTime}, is_deleted #{isDeleted}, person_oss_url #{personOssUrl}, lj_person_id #{ljPersonId}/setwhere device_no #{deviceNo} and pass_time #{passTime}/if/insert潜在问题这种“先查后写”的方式不是原子操作。在高并发场景下两个请求可能同时查到count 0然后都执行 insert导致重复数据。更稳妥的方案给业务唯一键加数据库唯一索引然后使用INSERTINTO...ONDUPLICATEKEYUPDATE...或者使用其他数据库层面的原子 upsert 语法。这样可以避免并发下的重复插入问题。四、MySQL 时间字段自动维护建表时经常使用created_timedatetimeDEFAULTCURRENT_TIMESTAMPCOMMENT创建时间,updated_timedatetimeDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMPCOMMENT修改时间这样可以实现插入时自动填充created_time更新时自动刷新updated_time。不过要注意如果业务代码里显式传入了这两个字段可能会覆盖数据库的默认行为。需要根据实际场景决定是否由数据库维护时间。总结本文整理了几个开发中容易踩坑的点MyBatisselectKey的keyProperty必须有对应 setter动态 SQL 条件不成立时可能生成空 SQL导致Query was empty先 count 再 insert/update 存在并发重复插入风险推荐唯一索引 原子 upsertMySQL 时间字段可以用DEFAULT CURRENT_TIMESTAMP和ON UPDATE CURRENT_TIMESTAMP自动维护愿你我都能在各自的领域里不断成长勇敢追求梦想同时也保持对世界的好奇与善意!
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/18 21:21:17

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/18 14:20:46

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/18 20:01:42

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/18 11:04:06

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/18 15:55:22

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/18 21:21:16

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉