mybatis @Select if
时间: 2023-10-01 16:09:19 浏览: 99
详解Mybatis中的select方法
Sure! In MyBatis, the `@Select` annotation is used to declare a SELECT statement in a mapper interface or XML mapper file. It is used to retrieve data from the database.
Here's an example of how to use `@Select` annotation in MyBatis:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(int id);
}
```
In this example, the `@Select` annotation is used to define a SELECT statement that retrieves a user from the database based on the given ID.
You can also use dynamic SQL in `@Select` annotation by using MyBatis's expression language. For example:
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE 1=1"
+ "<if test='name != null'> AND name = #{name}</if>"
+ "<if test='age != null'> AND age = #{age}</if>")
List<User> getUsersByNameAndAge(@Param("name") String name, @Param("age") Integer age);
}
```
In this example, the `@Select` annotation is used with dynamic SQL. The SQL query is constructed based on the provided parameters, and the conditions are only added if the corresponding parameter values are not null.
I hope this answers your question! Let me know if you have any further queries.
阅读全文