mybatis <if else
时间: 2023-10-21 12:57:57 浏览: 320
MyBatis provides a powerful feature called dynamic SQL, which allows you to conditionally include or exclude parts of a SQL statement using the `<if>` and `<choose>` tags. The `<if>` tag is used for conditional statements, including the usage of "if-else" logic.
Here's an example of how you can use `<if>` and `<choose>` tags in MyBatis:
```xml
<select id="getUserList" resultType="User">
SELECT * FROM users
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
<choose>
<when test="order == 'name'">
ORDER BY name
</when>
<when test="order == 'age'">
ORDER BY age
</when>
<otherwise>
ORDER BY id
</otherwise>
</choose>
</where>
</select>
```
In this example, the `<if>` tags are used to conditionally add the corresponding SQL clauses based on the provided parameters. The `<choose>` tag acts as an "if-else" statement, where the first matching `<when>` condition is executed, and if none of the conditions match, the `<otherwise>` block is executed.
So, depending on the values of the `name`, `age`, and `order` parameters, the generated SQL query will vary accordingly.
阅读全文