超爱学习网
mybatisPlus
一级目录
基础使用
常用注解
构造器类型
条件类型
curd接口
插件扩展
面试题
参考手册
版本
二级目录
构造器类型
QueryWrapper
UpdateWrapper
LambdaQueryWrapper
LambdaUpdateWrapper
QueryChainWrapper
UpdateChainWrapper
AbstractWrapper
EntityWrapper

UpdateChainWrapper 概念和作用

UpdateChainWrapper 是 MyBatis-Plus 中用于构建和执行更新操作的工具。它提供了链式编程方法来构建 SQL 更新语句,使得更新数据库中的数据变得更简单、更直观。它支持多种更新操作,包括设置字段值、条件过滤、批量更新等。

1. 基本更新

// 更新用户名为 'John' 的用户的年龄为 30
new UpdateChainWrapper<>(User.class)
  .eq("name", "John")
  .set("age", 30)
  .update();

2. 条件更新

// 将年龄大于 18 且用户名为 'John' 的用户的状态设为激活
new UpdateChainWrapper<>(User.class)
  .gt("age", 18)
  .eq("name", "John")
  .set("status", "active")
  .update();

3. 批量更新

// 将所有用户的状态设置为激活
new UpdateChainWrapper<>(User.class)
  .set("status", "active")
  .update();

4. 更新特定字段

// 更新用户名为 'John' 的用户的邮箱
new UpdateChainWrapper<>(User.class)
  .eq("name", "John")
  .set("email", "john@example.com")
  .update();

5. 排他更新

// 将用户名为 'John' 且年龄大于 30 的用户的状态设为非激活
new UpdateChainWrapper<>(User.class)
  .eq("name", "John")
  .gt("age", 30)
  .set("status", "inactive")
  .update();

6. 条件更新与排除字段

// 更新所有用户的信息,但不更新邮箱字段
new UpdateChainWrapper<>(User.class)
  .set("name", "Updated Name")
  .set("age", 25)
  .update(new UpdateWrapper<User>().excludeColumns("email"));

7. 动态设置更新值

// 根据用户的当前状态动态更新其状态
new UpdateChainWrapper<>(User.class)
  .setSql("status = CASE WHEN status = 'active' THEN 'inactive' ELSE 'active' END")
  .update();

8. 多字段更新

// 更新用户名为 'John' 的用户的年龄和邮箱
new UpdateChainWrapper<>(User.class)
  .eq("name", "John")
  .set("age", 35)
  .set("email", "newjohn@example.com")
  .update();

9. 有条件的批量更新

// 将年龄在 20 到 30 之间的用户的状态更新为激活
new UpdateChainWrapper<>(User.class)
  .between("age", 20, 30)
  .set("status", "active")
  .update();

10. 链式组合复杂更新

// 复杂条件组合:将年龄大于 18 并且名字包含 'John' 的用户的状态更新为激活
new UpdateChainWrapper<>(User.class)
  .gt("age", 18)
  .like("name", "John")
  .set("status", "active")
  .update();