MyBatis动态SQL与关联查询实战指南
1. MyBatis动态SQL的实战应用MyBatis作为Java生态中最受欢迎的ORM框架之一其动态SQL功能在实际开发中扮演着重要角色。动态SQL本质上是通过XML配置或注解方式根据运行时条件动态生成SQL语句的技术。这种机制完美解决了传统JDBC开发中需要手动拼接SQL字符串的痛点。1.1 核心动态元素解析MyBatis提供了多种动态SQL元素每个元素都有其特定的使用场景if最基本的条件判断元素test属性接收OGNL表达式select idfindActiveBlogWithTitleLike resultTypeBlog SELECT * FROM BLOG WHERE state ACTIVE if testtitle ! null AND title like #{title} /if /selectchoose/when/otherwise实现类似Java中的switch-case逻辑select idfindActiveBlogLike resultTypeBlog SELECT * FROM BLOG WHERE state ACTIVE choose when testtitle ! null AND title like #{title} /when when testauthor ! null and author.name ! null AND author_name like #{author.name} /when otherwise AND featured 1 /otherwise /choose /selecttrim/where/set智能处理SQL语句前后缀update idupdateAuthorIfNecessary update Author set if testusername ! nullusername#{username},/if if testpassword ! nullpassword#{password},/if if testemail ! nullemail#{email},/if if testbio ! nullbio#{bio}/if /set where id#{id} /updateforeach处理集合迭代常用于IN条件select idselectPostIn resultTypedomain.blog.Post SELECT * FROM POST P WHERE ID in foreach itemitem indexindex collectionlist open( separator, close) #{item} /foreach /select1.2 动态SQL的性能优化策略动态SQL虽然灵活但不当使用可能导致性能问题。以下是几个关键优化点避免过度动态化频繁的条件判断会增加SQL解析开销。对于固定条件尽量使用静态SQL。合理使用OGNL表达式复杂的OGNL表达式会影响解析性能建议将复杂逻辑移到Java代码中预处理使用bind元素缓存中间结果select idselectBlogsLike resultTypeBlog bind namepattern value% title % / SELECT * FROM Blog WHERE title LIKE #{pattern} /select批量操作优化对于批量插入/更新使用foreach时注意MySQL建议每批次控制在1000条以内可配置rewriteBatchedStatementstrue提升性能考虑使用MyBatis的批量执行器SQL片段复用使用sql和include减少重复代码sql iduserColumnsid,username,password/sql select idselectUsers resultTypemap select include refiduserColumns/ from some_table /select2. 一对一关联查询的深度实践一对一关系是数据库设计中常见的关系类型如用户与身份证、订单与发票等。MyBatis提供了多种实现一对一查询的方式。2.1 嵌套结果映射实现这是最高效的一对一查询方式通过单条SQL联合查询实现resultMap idblogResult typeBlog id propertyid columnblog_id / result propertytitle columnblog_title/ association propertyauthor javaTypeAuthor id propertyid columnauthor_id/ result propertyusername columnauthor_username/ result propertypassword columnauthor_password/ /association /resultMap select idselectBlog resultMapblogResult select B.id as blog_id, B.title as blog_title, A.id as author_id, A.username as author_username, A.password as author_password from Blog B left outer join Author A on B.author_id A.id where B.id #{id} /select关键点说明使用association标签定义关联对象通过列别名避免字段冲突左连接确保即使没有关联记录也能返回主表数据2.2 嵌套查询实现这种方式通过两条SQL实现适合关联表数据量大的场景resultMap idblogResult typeBlog association propertyauthor columnauthor_id javaTypeAuthor selectselectAuthor/ /resultMap select idselectBlog resultMapblogResult SELECT * FROM BLOG WHERE ID #{id} /select select idselectAuthor resultTypeAuthor SELECT * FROM AUTHOR WHERE ID #{id} /select性能考量会产生N1查询问题可通过FetchType.LAZY实现延迟加载MyBatis配置中开启lazyLoadingEnabledtrue2.3 注解方式实现对于偏好注解的开发者MyBatis提供了One注解public class Blog { private Integer id; private String title; One(select org.mybatis.example.AuthorMapper.selectAuthor) private Author author; //... }适用场景简单关联关系项目规模较小开发人员更熟悉注解方式3. 一对多关联查询的复杂场景处理一对多关系如博客与评论、部门与员工等是业务系统中更常见的关联关系。3.1 集合的嵌套结果映射resultMap idblogResult typeBlog id propertyid columnblog_id / result propertytitle columnblog_title/ collection propertyposts ofTypePost id propertyid columnpost_id/ result propertysubject columnpost_subject/ result propertybody columnpost_body/ /collection /resultMap select idselectBlog resultMapblogResult select B.id as blog_id, B.title as blog_title, P.id as post_id, P.subject as post_subject, P.body as post_body from Blog B left outer join Post P on B.id P.blog_id where B.id #{id} /select注意事项使用collection标签定义集合属性ofType指定集合元素类型主表id需要在SQL中明确指定避免结果集合并错误3.2 分页查询时的特殊处理当主查询需要分页时一对多关联会导致分页不准确。解决方案内存分页先获取主表分页数据再单独查询关联数据PageHelper.startPage(1, 10); // 只对下一个查询有效 ListBlog blogs blogMapper.selectBlogList(); blogs.forEach(blog - { blog.setComments(commentMapper.selectByBlogId(blog.getId())); });使用子查询在SQL层面限制主表数据select idselectBlogList resultMapblogResult select * from Blog where id in ( select id from Blog limit #{offset}, #{pageSize} ) /select3.3 多层嵌套关联查询对于复杂的对象图MyBatis支持多级嵌套resultMap iddetailedBlogResultMap typeBlog id propertyid columnblog_id/ result propertytitle columnblog_title/ association propertyauthor javaTypeAuthor id propertyid columnauthor_id/ result propertyusername columnauthor_username/ collection propertyposts ofTypePost id propertyid columnpost_id/ result propertysubject columnpost_subject/ collection propertycomments ofTypeComment id propertyid columncomment_id/ /collection /collection /association /resultMap性能建议超过3层嵌套应考虑DTO方式使用sql片段保持可读性考虑使用MyBatis-Plus的连表查询功能4. 高级应用与性能调优4.1 动态SQL与关联查询结合在实际业务中动态SQL常与关联查询结合使用select idselectBlogWithComments resultMapblogWithCommentsResult SELECT b.*, c.* FROM blog b LEFT JOIN comment c ON b.id c.blog_id where if teststate ! null b.state #{state} /if if testtitle ! null AND b.title like #{title} /if if testauthor ! null AND b.author_id #{author.id} /if /where ORDER BY b.id /select4.2 延迟加载策略优化MyBatis的延迟加载能显著提升性能settings setting namelazyLoadingEnabled valuetrue/ setting nameaggressiveLazyLoading valuefalse/ setting namelazyLoadTriggerMethods value/ /settings配置说明lazyLoadingEnabled开启延迟加载aggressiveLazyLoading设置为false避免不需要的属性加载lazyLoadTriggerMethods空字符串表示只有直接访问才会触发加载4.3 结果集自动映射的高级配置MyBatis 3.2.3支持更灵活的自动映射resultMap iduserResultMap typeUser autoMappingtrue id propertyid columnuser_id/ result propertyusername columnuser_name/ association propertyrole javaTypeRole autoMappingtrue/ /resultMap使用技巧主表可使用autoMapping减少配置关联对象也可单独设置autoMapping配合列别名避免字段冲突4.4 MyBatis-Plus对关联查询的增强MyBatis-Plus提供了更简洁的关联查询方式// 连表查询 ListUser users userMapper.selectJoinPage( new Page(1, 10), Wrappers.Userquery().eq(u.status, 1) ); // 分页查询关联数据 IPageUser page userMapper.selectUserPage( new Page(1, 10), new UserQueryParam() ); page.getRecords().forEach(user - { user.setRoles(roleMapper.selectByUserId(user.getId())); });优势减少XML配置内置分页插件支持Lambda表达式在实际项目中应根据业务复杂度、团队习惯和技术栈选择合适的实现方式。对于简单关联注解方式更便捷复杂业务场景XML配置提供了更强大的表达能力。无论哪种方式都应关注N1查询问题合理使用延迟加载和批量查询优化性能。

相关新闻

告别文档地狱:Apifox接口文档自动化生成与团队协作实战指南

告别文档地狱:Apifox接口文档自动化生成与团队协作实战指南

1. 从“文档地狱”到“文档自由”:为什么我们需要Apifox如果你是一名后端开发、前端开发或者测试工程师,那么“接口文档”这四个字,大概率是你职业生涯中一个永恒的痛点。我经历过太多这样的场景:项目初期,大家口头约定…

2026/11/13 14:23:39 阅读更多 →
嵌入式开发选型指南:CoreMark跑分实测ESP32、STM32与Arduino性能对比

嵌入式开发选型指南:CoreMark跑分实测ESP32、STM32与Arduino性能对比

1. 项目缘起:为什么嵌入式开发者需要关注CoreMark跑分? 最近在几个嵌入式开发群里,看到不少朋友在讨论ESP32、Arduino Uno R3和STM32F103C8T6(也就是大家常说的“蓝板”)的性能对比。讨论来讨论去,最后往往…

2026/11/13 17:17:32 阅读更多 →
P1564 膜拜【洛谷算法习题】

P1564 膜拜【洛谷算法习题】

P1564 膜拜 网页链接 P1564 膜拜 题目描述 神牛有很多…当然…每个同学都有自己衷心膜拜的神牛。 某学校有两位神牛,神牛甲和神牛乙。新入学的 nnn 位同学们早已耳闻他们的神话。 所以,已经衷心地膜拜其中一位了。现在,老师要给他们分…

2026/11/12 5:33:06 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/15 5:13:35 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/15 5:13:35 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/15 5:13:35 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/15 3:37:41 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/15 4:18:38 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/15 5:13:35 阅读更多 →

日新闻

周新闻

月新闻