动态 SQL
当通过 Mapper XML 文件配置 SQL 时,允许通过 if、choose、foreach 等标签对 SQL进行动态配置。dbVisitor 采用了和 MyBatis 相同的风格。
- <if> 标签,用于判断某个条件满足。
- <choose>、<when>、<otherwise> 标签,多分支条件选择。
- <trim>、<where>、<set> 标签,用于生成结构正确的条件或 SET 片段。
- <foreach> 标签,foreach。
- <bind> 标签,通过 ognl 表达式创建变量并绑定到上下文。
if 标签
<if> 用于判断某个条件满足之后拼接对应的 SQL。
<select id="queryUser">
select * from users
where state = 'ACTIVE'
<if test="age != null">
and age = #{age}
</if>
</select>
单纯的 if 判断可以使用规则来替代,例如:
<select id="queryUser">
select * from users
where state = 'ACTIVE'
@{and, age = #{age}}
</select>
- 了解 AND 规则
标签属性
| 属性名 | 描述 |
|---|---|
| test | 必选,一个 ognl 表达式,表达式值是 boolean 表示判断是否成立,若判断成立则执行 SQL 生成。 |