MP(mybatis plus)已经大大简化了我们好多的开发操作,基本的增删改查都有了,包括代码生成等等,今天想说的是它的逻辑删除功能。我们都在数据库设计时候经常会有isDel字段,表示是否删除,为了留下客户数据,而只做逻辑删除,不做物理删除,但是MP默认的配置是物理删除,即直接调用的数据库delete操作,但是可以通过配置使调用MP的deleteXXX得方法时底层调用update操作。(以下以springboot为例)
添加配置
#逻辑删除配置
mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector
mybatis-plus.global-config.logic-delete-value=1
mybatis-plus.global-config.logic-not-delete-value=0
添加实体类注解
@TableLogic
private String isDel;
测试
调用者
此处有两个数据库操作,一个根据id查询,一个删除,期望输出两个sql,且第二个删除调用update方法。因为我的是服务间调用,如下
@ResponseBody
@RequestMapping("get-and-del")
public ResultModel<Boolean> getAndDel(@RequestParam("id")String id){
SysRole role = roleService.getById(id).getData();
System.out.println("json role --- >"+ FastJsonUtils.toJSONString(role));
return roleService.delById(id);
}
被调用
@RequestMapping("get-by-id")
public ResultModel<SysRole> getById(@RequestParam("id")String id){
return new ResultModel<>(ResultStatus.SUCCESS,roleService.selectById(id));
}
@RequestMapping("del-by-id")
public ResultModel<Boolean> delById(@RequestParam("id")String id){
return new ResultModel<>(ResultStatus.SUCCESS,roleService.deleteById(id));
}
测试结果

确实两句sql,第二个调用了update操作。重点来了,我们看上面一个根据id查询得方法,最后拼接上了 is_del='0'.
因为我们配置了逻辑删除之后,MP自带的查询以及Update方法后都会自动加上is_del='0'判断。
执行前后数据库对比


网友评论