mybatis-plus update用法 querymapper
时间: 2023-06-28 22:15:39 浏览: 61
MyBatis-Plus 提供了 QueryMapper 接口,它是一个通用的 Mapper 接口,用于提供通用的 CRUD 操作。其中,update 方法可以通过传入一个 UpdateWrapper 或者 LambdaUpdateWrapper 对象来构造更新条件,然后执行更新操作。
以下是一个使用 QueryMapper 的 update 方法来更新的例子:
```java
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", 1L)
.set("name", "张三")
.set("age", 20);
int rows = queryMapper.update(null, updateWrapper);
```
这段代码会生成类似于以下的 SQL 语句:
```sql
UPDATE user SET name = '张三', age = 20 WHERE id = 1
```
其中,`UpdateWrapper` 的 `eq` 方法用于设置更新的条件,`set` 方法用于设置要更新的字段和值。
需要注意的是,如果你使用了 `UpdateWrapper` 对象来构造更新条件,则不需要在 SQL 语句中写 `SET` 关键字。
另外,需要注意的是,在使用 QueryMapper 的时候,需要在 `@MapperScan` 注解中指定通用的 Mapper 接口的路径,例如:
```java
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
其中,`com.example.mapper` 是通用 Mapper 接口的包路径。