Skip to content

修改(update)

Mapper 内置方法

  • update(T):实体类修改
  • update(T,boolean):实体类修改(boolean为是否null值也修改)
  • update(Model):Model类修改
  • update(Model,boolean):Model类修改(boolean为是否null值也修改)
  • saveOrUpdate(T):实体类保存或修改
  • saveOrUpdate(T,boolean):实体类保存或修改(boolean为是否null值也修改)
  • saveOrUpdate(Model):Model类保存或修改
  • saveOrUpdate(Model,boolean):Model类保存或修改(boolean为是否null值也修改)
  • update(T,forceUpdateFields):实体类修改,可强制某些字段修改(null值会被替换层数据库里的NULL)
  • update(Model,forceUpdateFields):Model修改,可强制某些字段修改(null值会被替换层数据库里的NULL)
  • update(T,Where):根据where,实体类批量修改
  • update(T,boolean,Where):根据where,实体类批量修改(boolean为是否null值也修改)
  • update(Model,Where):根据where,Model类批量修改
  • update(Model,boolean,Where):根据where,Model类批量修改(boolean为是否null值也修改)
  • update(List<T>):多个实体类修改
  • update(List<T>,boolean):多个实体类修改(boolean为是否null值也修改)
  • updateModel(List<Model>):多个Model类修改
  • updateModel(List<Model>,boolean):多个Model类修改(boolean为是否null值也修改)
  • update(List<T>,forceUpdateFields):多个实体类修改,可强制某些字段修改(null值会被替换层数据库里的NULL)

基于实体类

java
public class Demo {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    public void update() {
        SysUser sysUser = new SysUser();
        sysUser.setId(1);
        sysUser.setUserName("demo");
        sysUserMapper.update(sysUser);
    }
}

基于Model类

Model类为了update时,不用处理太多的字段,只修改部分字段;同时也简单类的转换,方便快捷

Model类

java
@Data
public class SysUserModel implements Model<SysUser> {

    private Integer id;

    private String userName;
   
    
    //private String password;

    //private Integer roleId;

    private LocalDateTime createTime;
}

基于Model类 update

java
public class Demo {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    public void update() {
        SysUserModel sysUser = new SysUserModel();
        sysUser.setId(1);
        sysUser.setUserName("demo");
        sysUserMapper.update(sysUser);
    }
}

动态update

基于UpdateChain(强大)

可构建复杂的场景

java
public class Demo {
    @Autowired
    private SysUserMapper sysUserMapper;

    public void update() {
        UpdateChain.of(sysUserMapper)
                .update(SysUser.class)
                .set(SysUser::getUserName, "new userName")
                .eq(SysUser::getId, 1)
                .execute();
    }
}

基于where,(批量)修改

java
public class Demo {
    @Autowired
    private SysUserMapper sysUserMapper;

    public void update() {
        SysUser sysUser=new SysUser();
        sysUser.setUserName("where UPDATE");
        sysUserMapper.update(sysUser,where -> {
            where.gt(SysUser::getId,100);
        });
    }
}

update 列自增,例如version=version +1

也可以 其他自身操作

java
public class Demo {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    public void update() {
        UpdateChain.of(sysUserMapper)
            .set(SysUser::getVersion, (Function<TableField, Cmd>) c -> c.plus(1))
            .eq(SysUser::getId, 1)
            .execute();
    }
}