业务中遇到一种场景,需要从数据表中查询出一条记录,将其中一个字段更新一个值,以下三种方式:
//Mybatis-plus内置更新方法
@Override
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
public boolean updateById(T entity) {
return retBool(baseMapper.updateById(entity));
}
}
第一种:
Information information=informationService.getInfoDetailById(infoId);//使用Mybatis-plus内置sql
information.setInfoStatus(0);
informationService.updateById(information);//使用Mybatis-plus内置sql更新
这种方法操作起来最简单,但是使用Mybatis-plus内置sql更新时,会比较全量字段有没有改变,再进行更新
第二种:
Information information=informationService.getInfoDetailById(infoId);//使用Mybatis-plus内置sql
Information temp=new Information();
temp.setInfoId(information.getInfoId());
temp.setInfoStatus(0);
informationService.updateById(temp);//使用Mybatis-plus内置sql更新
这种方法比第一种方法需要多创建一个Information 对象,更新数据表时只判断更新改变的字段
第三种:
Information information=informationService.getInfoDetailById(infoId);//使用Mybatis-plus内置sql
int infoId=information.getInfoId();
informationService.myUpdate(infoId,0);
@Update("update information set status=#{status} where infoId=#{infoId}")
void myUpdate(int infoId,int status);
这种方法不用new对象,也不会更新多余字段,就是自己写sql比较麻烦
你们会选择那种呢?