动态 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 生成。 |
choose (when, otherwise) 标签
当有条件被满足之后会生成对应 <when> 中的 SQL,如果有多个条件同时匹配,只有第一个会生效。若没有匹配任何 <when> 那么 <otherwise> 会生效。
<select id="queryUser">
select * from users
where state = 'ACTIVE'
<choose>
<when test="title != null">and title = #{title}</when>
<when test="content != null">and content = #{content}</when>
<otherwise>and owner = 'owner1'</otherwise>
</choose>
</select>
标签属性
<choose> 和 <otherwise> 不含有任何属性。<when> 属性如下:
| 属性名 | 描述 |
|---|---|
| test | 必选,一个 ognl 表达式,表达式值是 boolean 表示判断是否成立,若判断成立则执行 SQL 生成。 |
trim (where, set) 标签
<trim>、<where>、<set> 三个标签用于生成结构正确的 SQL 片段。以下示例展示未使用这些标签时容易出现的问题:
<select id="queryUser">
select * from users
where
<if test="age != null">
and age = #{age}
</if>
</select>
当 age 属性为空时会生成如下 SQL。
select * from users
where
这是一个无效 SQL,若想避免此类问题可以选择 <where> 。