mybatisplus使用if else
时间: 2023-10-02 14:04:52 浏览: 81
MyBatis Plus provides a convenient way to use if-else conditions in SQL queries. You can use the `@if` annotation to conditionally include a part of the SQL statement based on a specified condition. Here's an example of how to use if-else conditions with MyBatis Plus:
1. First, you need to import the necessary annotations in your mapper interface:
```java
import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
```
2. Then, define your SQL query in the mapper interface using the `@Select` annotation:
```java
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user " +
"WHERE 1=1" +
"<if test=\"name != null and name != ''\">" +
"AND name = #{name}" +
"</if>" +
"<if test=\"age != null\">" +
"AND age = #{age}" +
"</if>")
List<User> getUsers(@Param("name") String name, @Param("age") Integer age);
}
```
In this example, the SQL query selects all users from the `user` table. However, the `name` and `age` conditions are included only if the corresponding parameters are not null. The `@Param` annotation is used to map the method parameters to the SQL query parameters.
3. Finally, you can use this method in your service or controller:
```java
@Autowired
private UserMapper userMapper;
public List<User> searchUsers(String name, Integer age) {
return userMapper.getUsers(name, age);
}
```
When calling the `searchUsers` method, you can pass the `name` and `age` parameters to filter the results accordingly.
This is just a basic example of using if-else conditions in MyBatis Plus. You can also use other conditional annotations like `@when`, `@otherwise`, and `@choose` for more complex scenarios.