mybatis if else怎么写
时间: 2023-09-28 11:07:15 浏览: 42
在 MyBatis 中,我们可以使用 \<if> 元素来编写 if-else 语句。
假设我们有一个用户查询的 SQL,如果参数中有用户名和邮箱地址,那么就按照用户名查询;如果只有邮箱地址,就按照邮箱地址查询;如果都没有,就查询所有用户。我们可以使用以下语句:
```xml
<select id="getUserList" parameterType="User" resultType="User">
SELECT * FROM user
<where>
<if test="username != null and username != ''">
AND username = #{username}
</if>
<if test="email != null and email != ''">
AND email = #{email}
</if>
</where>
</select>
```
在这个例子中,我们使用了 \<if> 元素来判断是否需要添加查询条件。test 属性中的表达式返回 true 或 false,如果返回 true,就会添加 if 元素内部的 SQL 语句。在这个例子中,如果 username 参数不为空,就会添加 AND username = #{username} 的 SQL 语句,否则不会添加。同理,如果 email 参数不为空,就会添加 AND email = #{email} 的 SQL 语句。
需要注意的是,如果有多个 \<if> 元素,它们之间默认是 and 关系,会同时判断所有的条件。如果需要 or 关系,可以使用 \<choose>、\<when> 和 \<otherwise> 元素来实现。例如:
```xml
<select id="getUserList" parameterType="User" resultType="User">
SELECT * FROM user
<where>
<choose>
<when test="username != null and username != ''">
AND username = #{username}
</when>
<when test="email != null and email != ''">
AND email = #{email}
</when>
<otherwise>
AND 1=1
</otherwise>
</choose>
</where>
</select>
```
在这个例子中,\<choose> 元素相当于 switch 语句,如果第一个 \<when> 的 test 表达式返回 true,就添加 AND username = #{username} 的 SQL 语句;如果第二个 \<when> 的 test 表达式返回 true,就添加 AND email = #{email} 的 SQL 语句;否则添加 AND 1=1 的 SQL 语句,相当于查询所有用户。