
本文详解如何在 Spring Boot + MyBatis 项目中,通过扩展实体类与灵活使用 、 等动态 SQL 标签,支持 =, >,
本文详解如何在 spring boot + mybatis 项目中,通过扩展实体类与灵活使用 ` 在实际业务开发中,仅靠 age = #{student.age} 这类静态等值条件远远无法满足前端分页筛选、管理后台高级搜索等场景需求。例如:用户可能希望查询“年龄大于18”、“姓名包含‘张’”、“年级在2021–2023之间”或“状态为启用/禁用”的学生列表。此时,必须将查询逻辑从“字段直传”升级为“条件语义化建模”。 最轻量且可维护性高的做法是扩展查询 DTO(如 StudentQuery),避免污染核心实体 Student。例如: 对应 MyBatis XML 中编写结构清晰的动态 SQL: ⚠️ 注意事项: 当同一字段需支持多种互斥语义时(例如:age 字段支持 =, >, BETWEEN 三选一),可用 配合 Java 类: 通过合理设计查询参数模型与精准运用 MyBatis 动态 SQL,你不仅能优雅支持多样化查询需求,还能显著提升代码可读性、可测试性与安全性。记住:好的查询接口,始于清晰的契约设计,成于严谨的 SQL 构建。✅ 推荐方案:引入条件封装字段(推荐用于简单范围与基础运算)
public class StudentQuery {
private String name; // 支持模糊匹配
private Integer minAge; // age >= minAge
private Integer maxAge; // age <= maxAge
private List<String> statuses; // status IN (...)
private String orderBy; // 动态排序字段(可选)
private String orderDir; // ASC / DESC(可选)
private Pageable pageable;
// getter/setter...
}<select id="listStudent" resultType="Student">
SELECT * FROM student
<where>
<if test="query.name != null and query.name != ''">
AND name LIKE CONCAT('%', #{query.name}, '%')
</if>
<if test="query.minAge != null">
AND age >= #{query.minAge}
</if>
<if test="query.maxAge != null">
AND age <= #{query.maxAge}
</if>
<if test="query.statuses != null and query.statuses.size() > 0">
AND status IN
<foreach item="status" collection="query.statuses" open="(" separator="," close=")">
#{status}
</foreach>
</if>
</where>
<if test="query.orderBy != null and query.orderDir != null">
ORDER BY ${query.orderBy} ${query.orderDir}
</if>
</select>
✅ 进阶方案:使用
<if test="query.ageCondition != null">
<choose>
<when test="query.ageCondition.type == 'EQ'">
AND age = #{query.ageCondition.value}
</when>
<when test="query.ageCondition.type == 'GT'">
AND age > #{query.ageCondition.value}
</when>
<when test="query.ageCondition.type == 'BETWEEN'">
AND age BETWEEN #{query.ageCondition.min} AND #{query.ageCondition.max}
</when>
</choose>
</if>public class AgeCondition {
private String type; // EQ / GT / BETWEEN
private Integer value;
private Integer min;
private Integer max;
}✅ 最佳实践总结
场景
推荐方式
说明
简单范围(≥/≤)
扩展 minXxx / maxXxx 字段
语义清晰、零学习成本、易于前端对接
多种运算符互斥
避免条件叠加歧义,适合高级搜索面板
全文/模糊/正则
LIKE + CONCAT 或数据库全文索引
避免 %${xxx}% 直接拼接(SQL注入风险)
枚举/状态批量筛选
注意空集合判空,防止生成 IN () 报错
安全与可维护性
绝不滥用 ${};所有用户输入一律用 #{} 绑定;复杂条件抽取为独立 Query DTO
是长期项目稳定性的基石










