1. MyBatis动态SQL的实战应用
MyBatis作为Java生态中最受欢迎的ORM框架之一,其动态SQL功能在实际开发中扮演着重要角色。动态SQL本质上是通过XML配置或注解方式,根据运行时条件动态生成SQL语句的技术。这种机制完美解决了传统JDBC开发中需要手动拼接SQL字符串的痛点。
1.1 核心动态元素解析
MyBatis提供了多种动态SQL元素,每个元素都有其特定的使用场景:
<if>:最基本的条件判断元素,test属性接收OGNL表达式
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <if test="title != null"> AND title like #{title} </if> </select><choose>/<when>/<otherwise>:实现类似Java中的switch-case逻辑
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select><trim>/<where>/<set>:智能处理SQL语句前后缀
<update id="updateAuthorIfNecessary"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update><foreach>:处理集合迭代,常用于IN条件
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>1.2 动态SQL的性能优化策略
动态SQL虽然灵活,但不当使用可能导致性能问题。以下是几个关键优化点:
避免过度动态化:频繁的条件判断会增加SQL解析开销。对于固定条件,尽量使用静态SQL。
合理使用OGNL表达式:复杂的OGNL表达式会影响解析性能,建议:
- 将复杂逻辑移到Java代码中预处理
- 使用
<bind>元素缓存中间结果
<select id="selectBlogsLike" resultType="Blog"> <bind name="pattern" value="'%' + title + '%'" /> SELECT * FROM Blog WHERE title LIKE #{pattern} </select>批量操作优化:对于批量插入/更新,使用
<foreach>时注意:- MySQL建议每批次控制在1000条以内
- 可配置
rewriteBatchedStatements=true提升性能 - 考虑使用MyBatis的批量执行器
SQL片段复用:使用
<sql>和<include>减少重复代码
<sql id="userColumns">id,username,password</sql> <select id="selectUsers" resultType="map"> select <include refid="userColumns"/> from some_table </select>2. 一对一关联查询的深度实践
一对一关系是数据库设计中常见的关系类型,如用户与身份证、订单与发票等。MyBatis提供了多种实现一对一查询的方式。
2.1 嵌套结果映射实现
这是最高效的一对一查询方式,通过单条SQL联合查询实现:
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <association property="author" javaType="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> </association> </resultMap> <select id="selectBlog" resultMap="blogResult"> 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 id="blogResult" type="Blog"> <association property="author" column="author_id" javaType="Author" select="selectAuthor"/> </resultMap> <select id="selectBlog" resultMap="blogResult"> SELECT * FROM BLOG WHERE ID = #{id} </select> <select id="selectAuthor" resultType="Author"> SELECT * FROM AUTHOR WHERE ID = #{id} </select>性能考量:
- 会产生N+1查询问题
- 可通过
@FetchType.LAZY实现延迟加载 - MyBatis配置中开启
lazyLoadingEnabled=true
2.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 id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <collection property="posts" ofType="Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="body" column="post_body"/> </collection> </resultMap> <select id="selectBlog" resultMap="blogResult"> 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); // 只对下一个查询有效 List<Blog> blogs = blogMapper.selectBlogList(); blogs.forEach(blog -> { blog.setComments(commentMapper.selectByBlogId(blog.getId())); });- 使用子查询:在SQL层面限制主表数据
<select id="selectBlogList" resultMap="blogResult"> select * from Blog where id in ( select id from Blog limit #{offset}, #{pageSize} ) </select>3.3 多层嵌套关联查询
对于复杂的对象图,MyBatis支持多级嵌套:
<resultMap id="detailedBlogResultMap" type="Blog"> <id property="id" column="blog_id"/> <result property="title" column="blog_title"/> <association property="author" javaType="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <collection property="posts" ofType="Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <collection property="comments" ofType="Comment"> <id property="id" column="comment_id"/> </collection> </collection> </association> </resultMap>性能建议:
- 超过3层嵌套应考虑DTO方式
- 使用
<sql>片段保持可读性 - 考虑使用MyBatis-Plus的连表查询功能
4. 高级应用与性能调优
4.1 动态SQL与关联查询结合
在实际业务中,动态SQL常与关联查询结合使用:
<select id="selectBlogWithComments" resultMap="blogWithCommentsResult"> SELECT b.*, c.* FROM blog b LEFT JOIN comment c ON b.id = c.blog_id <where> <if test="state != null"> b.state = #{state} </if> <if test="title != null"> AND b.title like #{title} </if> <if test="author != null"> AND b.author_id = #{author.id} </if> </where> ORDER BY b.id </select>4.2 延迟加载策略优化
MyBatis的延迟加载能显著提升性能:
<settings> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> <setting name="lazyLoadTriggerMethods" value=""/> </settings>配置说明:
lazyLoadingEnabled:开启延迟加载aggressiveLazyLoading:设置为false避免不需要的属性加载lazyLoadTriggerMethods:空字符串表示只有直接访问才会触发加载
4.3 结果集自动映射的高级配置
MyBatis 3.2.3+支持更灵活的自动映射:
<resultMap id="userResultMap" type="User" autoMapping="true"> <id property="id" column="user_id"/> <result property="username" column="user_name"/> <association property="role" javaType="Role" autoMapping="true"/> </resultMap>使用技巧:
- 主表可使用
autoMapping减少配置 - 关联对象也可单独设置
autoMapping - 配合列别名避免字段冲突
4.4 MyBatis-Plus对关联查询的增强
MyBatis-Plus提供了更简洁的关联查询方式:
// 连表查询 List<User> users = userMapper.selectJoinPage( new Page<>(1, 10), Wrappers.<User>query().eq("u.status", 1) ); // 分页查询+关联数据 IPage<User> page = userMapper.selectUserPage( new Page<>(1, 10), new UserQueryParam() ); page.getRecords().forEach(user -> { user.setRoles(roleMapper.selectByUserId(user.getId())); });优势:
- 减少XML配置
- 内置分页插件
- 支持Lambda表达式
在实际项目中,应根据业务复杂度、团队习惯和技术栈选择合适的实现方式。对于简单关联,注解方式更便捷;复杂业务场景,XML配置提供了更强大的表达能力。无论哪种方式,都应关注N+1查询问题,合理使用延迟加载和批量查询优化性能。