mybatis-plus 通过 updateById 更新部分字段数据时出现所有数据被更新(被设为默认值)

  • Post author:
  • Post category:其他



int updateById(@Param(Constants.ENTITY) T entity);

通过传入的 id 进行数据更新,默认只更新设置数据的字段。

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("user")
public class User {
    @TableId("userId")
    private int userId;
    private String password;
    private int type;
}
@Mapper
public interface UserDao extends BaseMapper<User> {
}
//这个方法用来更新用户的密码,user对象之设置了id和password属性
@Override
public void updateUserPassword(int userId, String password) {
    User user = new User();
    user.setUserId(userId);
    user.setPassword(password);
    userDao.updateById(user); 
}

但当执行时发现 type 属性也被更新了,且为 int 默认值 0。


一顿百度,什么也没查到之后发现


需要设置 实体类 user 的 type 为 Integer,因为 int 不能为 null,而 Integer 可以。

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@TableName("user")
public class User {
    @TableId("userId")
    private Integer userId;
    private String password;
    private Integer type;
}



版权声明:本文为weixin_46376562原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。