mybatis <if> else
时间: 2023-10-28 15:24:23 浏览: 162
Mybatis provides a way to conditionally include SQL statements using the `<if>` and `<choose>` tags.
You can use the `<if>` tag to add a condition to your SQL query. Here's an example:
```xml
<select id="getUserById" resultType="User">
SELECT * FROM users
WHERE id = #{id}
<if test="name != null">
AND name = #{name}
</if>
</select>
```
In this example, the SQL query will include the additional `AND name = #{name}` condition only if the `name` parameter is not null.
You can also use the `<choose>` tag along with `<when>` and `<otherwise>` tags to implement conditional logic with multiple options. Here's an example:
```xml
<select id="getUserByCriteria" resultType="User">
SELECT * FROM users
WHERE
<choose>
<when test="name != null">
name = #{name}
</when>
<when test="email != null">
email = #{email}
</when>
<otherwise>
id = #{id}
</otherwise>
</choose>
</select>
```
In this example, the SQL query will check for different criteria based on the provided parameters. If `name` is not null, it will search by name. If `email` is not null, it will search by email. Otherwise, it will default to searching by ID.
These conditional tags provide flexibility in building dynamic SQL queries based on different conditions.
阅读全文