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查询问题合理使用延迟加载和批量查询优化性能。