MyBatis-Plus 按条件更新
所属分类 mybatis-plus
浏览量 102
按条件更新通常使用 UpdateWrapper 或 LambdaUpdateWrapper 构建更新条件,
结合实体类或 Map 设置更新字段
// 实体类
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// getter/setter...
}
1. 使用 UpdateWrapper 按条件更新
public boolean updateUserByCondition() {
// 1. 创建 UpdateWrapper 条件构造器
UpdateWrapper< User> updateWrapper = new UpdateWrapper< >();
// 2. 设置更新条件(例如:年龄等于25且邮箱不为空)
updateWrapper.eq("age", 25).isNotNull("email");
// 3. 创建实体对象并设置要更新的字段(非空字段会被更新)
User user = new User();
user.setName("John Doe"); // 只更新 name 字段
user.setEmail("john@example.com"); // 同时更新 email
// 4. 执行更新操作
int rows = userMapper.update(user, updateWrapper);
return rows > 0;
}
2. 使用 LambdaUpdateWrapper(推荐)
public boolean updateUserByLambdaCondition() {
// 1. 创建 LambdaUpdateWrapper(避免硬编码字段名)
LambdaUpdateWrapper< User> lambdaWrapper = new LambdaUpdateWrapper< >();
// 2. 设置条件(年龄等于25且邮箱不为空)
lambdaWrapper.eq(User::getAge, 25).isNotNull(User::getEmail);
// 3. 创建实体对象并设置更新字段
User user = new User();
user.setName("Jane Smith"); // 只更新 name 字段
// 4. 执行更新
int rows = userMapper.update(user, lambdaWrapper);
return rows > 0;
}
3. 使用 Map 设置更新字段
public boolean updateUserByMap() {
// 1. 创建 UpdateWrapper 条件
UpdateWrapper< User> updateWrapper = new UpdateWrapper< >();
updateWrapper.eq("age", 30);
// 2. 使用 Map 设置要更新的字段(动态字段)
Map< String, Object> updateMap = new HashMap< >();
updateMap.put("name", "Alice");
updateMap.put("email", "alice@example.com");
// 3. 执行更新
int rows = userMapper.update(null, updateWrapper.setMap(updateMap));
return rows > 0;
}
4. 注意事项
字段匹配:
实体类字段名需与数据库列名匹配(可通过 @TableId、@TableField 注解配置)
若字段名不一致,需在 UpdateWrapper 中使用 set(columnName, value) 明确指定数据库列名
更新字段规则:
实体类中 非空字段 会被更新到数据库(null 字段会被忽略)
若需强制更新为 null,需使用 UpdateWrapper 的 set(columnName, null)
返回值:
update 方法返回受影响的行数,需判断 rows > 0 确认更新是否成功
性能优化:
避免在条件中使用 1=1 或模糊匹配(如 like)导致全表扫描
5. 示例场景
按主键更新(推荐 updateById):
User user = new User();
user.setId(1L);
user.setName("New Name");
userMapper.updateById(user); // 直接通过主键更新
按组合条件更新:
LambdaUpdateWrapper< User> wrapper = new LambdaUpdateWrapper< >();
wrapper.eq(User::getName, "John").gt(User::getAge, 20);
User user = new User();
user.setEmail("john_new@example.com");
userMapper.update(user, wrapper);
上一篇
下一篇
金刚经 心经 与 投资交易
空不异色,色不异空 理解
坛经名句
佛的十个名号
阿耨多罗三藐三菩提 解释
金刚经名句及解析