mybatis if else
时间: 2023-09-04 12:17:21 浏览: 417
mybatis示例
MyBatis provides support for conditional logic using the `<if>` and `<choose>` elements. These elements allow you to conditionally include or exclude parts of your SQL statements based on certain conditions.
The `<if>` element is used to conditionally include a part of the SQL statement. It takes a test attribute that specifies the condition to be evaluated. If the condition evaluates to true, the content inside the `<if>` element is included in the SQL statement.
Here's an example of using the `<if>` element in MyBatis:
```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 `name` parameter is optional. If it is provided, the condition `name != null` evaluates to true, and the `AND name = #{name}` part is included in the SQL statement. If the `name` parameter is not provided or is null, that part is excluded.
The `<choose>` element is used to implement if-else logic. It contains one or more `<when>` elements and an optional `<otherwise>` element. The `<when>` elements specify conditions, and the content inside the first matching `<when>` element is included in the SQL statement. If none of the conditions evaluate to true, the content inside the `<otherwise>` element is included.
Here's an example of using the `<choose>` element in MyBatis:
```xml
<select id="getUserByCondition" resultType="User">
SELECT *
FROM users
WHERE
<choose>
<when test="id != null">
id = #{id}
</when>
<when test="name != null">
name = #{name}
</when>
<otherwise>
status = 'active'
</otherwise>
</choose>
</select>
```
In this example, the SQL statement will include either `id = #{id}` if the `id` parameter is provided, or `name = #{name}` if the `name` parameter is provided. If neither parameter is provided, the SQL statement will include `status = 'active'` as a default condition.
These conditional elements provide flexibility in constructing dynamic SQL statements based on different conditions in your application.
阅读全文