MybatisPlus-删除

目录

1.数据库建表 

2.项目 ---就是更新del_flag字段为2

(1)pom.xml

(2)Application

(3)applicatiom.yml

(4)entity

(5)mapper

(6)service

(7)service目录下的impl目录

 (8)common

(9)enums

(10)config

(11)controller

postman测试

3.彻底删除数据库记录

(11)controller

postman


MybatisPlus-删除_第1张图片

1.数据库建表 

CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '修改时间',
  `del_flag` tinyint(1) DEFAULT '1' COMMENT '删除状态:1正常/2删除',
  `user_id` varchar(255) DEFAULT NULL COMMENT '用户id',
  `user_name` varchar(255) DEFAULT NULL COMMENT '用户名称',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户信息';

2.项目 ---就是更新del_flag字段为2

(1)pom.xml



    4.0.0
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.5.RELEASE
    


    org.example
    mybatisplus1
    1.0-SNAPSHOT

    
        8
        8
        UTF-8

        
        1.18.16
        3.4.1
        1.1.23
    

    

        

        
        
            org.springframework.boot
            spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.springframework.boot
            spring-boot-starter-web
            compile
        

        
        
            org.projectlombok
            lombok
            ${lombok.version}
        

        
        
            mysql
            mysql-connector-java
            runtime
        

        
        
            com.alibaba
            druid-spring-boot-starter
            ${druid.version}
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            ${mybatis-plus.version}
        




    


    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                    com.lpc.Application
                    ZIP
                    true
                
                
                    
                        
                            repackage
                        
                    
                
            
        
    




(2)Application

package com.lpc;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author lpc
 * @Date 2024 01 11 11 38
 **/
@SpringBootApplication
@Slf4j
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
        log.info("项目启动成功......");
    }
}

(3)applicatiom.yml

server:
  port: 8888
spring:
  #连接数据库
  datasource:
    druid:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: lpc123456
mybatis-plus:
  configuration:
    #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

(4)entity

package com.lpc.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;


/**
 * @Author lpc
 * @Date 2024 01 11 14 08
 **/
@Data
@EqualsAndHashCode(callSuper = false)
public class SysUser implements Serializable {


    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 创建时间
     */
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    /**
     * 更新时间
     */
    @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

    /**
     * 删除状态默认1正常/2删除
     */
    private Integer delFlag;

    /**
     * 用户id
     */
    private String userId;

    /**
     * 用户名称
     */
    private String userName;

}

(5)mapper

package com.lpc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lpc.entity.SysUser;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Author lpc
 * @Date 2024 01 11 14 19
 **/
@Mapper
public interface SysUserMapper extends BaseMapper {
}

(6)service

package com.lpc.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.lpc.entity.SysUser;

/**
 * @Author lpc
 * @Date 2024 01 11 14 20
 **/
public interface SysUserService extends IService {
}

(7)service目录下的impl目录

package com.lpc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lpc.entity.SysUser;
import com.lpc.mapper.SysUserMapper;
import com.lpc.service.SysUserService;
import org.springframework.stereotype.Service;

/**
 * @Author lpc
 * @Date 2024 01 11 14 21
 **/
@Service
public class SysUserServiceImpl extends ServiceImpl implements SysUserService {
}

 (8)common

package com.lpc.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.lpc.enums.CodeEnum;
import lombok.Data;

import java.io.Serializable;

/**
 *  接口返回数据格式
 * @author scott
 */
@Data
public class Result implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * 成功标志
	 */
	private boolean success = true;

	/**
	 * 返回处理消息
	 */
	private String message = "操作成功!";

	/**
	 * 返回代码
	 */
	private Integer code = 0;

	/**
	 * 返回数据对象 data
	 */
	private T result;

	//返回数据
	private T data;
	/**
	 * 时间戳
	 */
	private long timestamp = System.currentTimeMillis();

	public Result(Integer code, String message, T result) {
		this.code=code;
		this.message=message;
		this.result=result;
	}
	public Result() {

	}

	public Result success(String message) {
		this.message = message;
		this.code = CodeEnum.SUCCESS.getCode();
		this.success = true;
		return this;
	}

	@Deprecated
	public static Result ok() {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setMessage("成功");
		return r;
	}

	@Deprecated
	public static Result ok(String msg) {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setMessage(msg);
		return r;
	}

	@Deprecated
	public static Result ok(Object data) {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setResult(data);
		return r;
	}

	public static Result OK() {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setMessage("成功");
		return r;
	}

	public static Result OK(T data) {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setResult(data);
		return r;
	}

	public static Result OK(String msg, T data) {
		Result r = new Result();
		r.setSuccess(true);
		r.setCode(CodeEnum.SUCCESS.getCode());
		r.setMessage(msg);
		r.setResult(data);
		return r;
	}

	public static Result error(String msg) {
		return error(CodeEnum.FAILURE.getCode(), msg);
	}

	public static Result error(int code, String msg) {
		Result r = new Result();
		r.setCode(code);
		r.setMessage(msg);
		r.setSuccess(false);
		return r;
	}

	public Result error500(String message) {
		this.message = message;
		this.code = CodeEnum.FAILURE.getCode();
		this.success = false;
		return this;
	}

	@JsonIgnore
	private String onlTable;

}
 
  

(9)enums

package com.lpc.enums;

/**
 * @ClassName CodeEnum
 * @Description 状态码
 */
public enum CodeEnum {

    /**
     * 处理成功
     */
    SUCCESS(200, "成功"),

    /**
     * 处理失败
     */
    FAILURE(422, "处理失败"),

    /**
     * 处理失败
     */
    PERMISSION_DENIED(403, "权限不足"),

    /**
     * 门户二维码轮训请求:未登录成功
     */
    QR_LOGIN_NOT_SUCCESS(1000, "未登录成功"),

    /**
     * 门户二维码轮训请求:二维码已过期
     */
    QR_LOGIN_OVERDUE(1001, "二维码已过期,请重新刷新"),

    /**
     * 全局异常
     */
    ERROR_1002(1002, "服务器错误,请联系管理员"),
    /**
     * 缺少必要参数
     */
    ERROR_1004(1004, "缺少必要参数"),
    /**
     * 参数类型错误
     */
    ERROR_1005(1005, "参数类型错误"),
    /**
     * 日期转换异常
     */
    ERROR_1006(1006, "日期格式错误"),
    /**
     * 没有权限,请联系管理员授权
     */
    SC_JEECG_NO_AUTHZ(510, "没有权限,请联系管理员授权"),
    /**
     * 数据库中已存在该记录
     */
    ERROR_1007(1007, "数据库中已存在该记录"),
    /**
     * 路径不存在,请检查路径是否正确
     */
    ERROR_404(404, "路径不存在,请检查路径是否正确"),
    /**
     * token失效
     */
    ERROR_1008(1008, "Token失效,请重新登录!"),
    /**
     * 用户不存在
     */
    ERROR_1009(1009, "用户不存在"),
    /**
     * 账号锁定
     */
    ERROR_1010(1010, "账号锁定"),

    /**
     * 指纹登录轮训请求,未登录成功
     */
    FINGERPRINT_LOGIN_NOT_SUCCESS(1011, "未登录成功");
    private final Integer code;

    private final String msg;


    CodeEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    /**
     * 根据 value 值反推 GlobalError
     *
     * @param value
     * @return
     */
    public static CodeEnum valueOf(int value) {
        for (CodeEnum right : CodeEnum.values()) {
            if (value == right.code) {
                return right;
            }
        }
        return null;
    }


}

(10)config

package com.lpc.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author lpc
 * @Date 2024 01 11 14 14
 *
 **/
@Component
@Slf4j
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 公共字段操作
     * 插入的时候进行操作的两个字段createTime,updateTime (自动)
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
    }
    /**
     *公共字段操作
     * 修改更新的时候只操作updateTime这个字段(自动)
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);
    }


    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

(11)controller

package com.lpc.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lpc.common.Result;
import com.lpc.entity.SysUser;
import com.lpc.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author lpc
 * @Date 2024 01 11 14 23
 **/
@RequestMapping("/lpc/user")
@RequiredArgsConstructor
@RestController
public class SysUserController {
    private final SysUserService userService;

   
  
    /**
     * 路径:localhost:8888/lpc/user/delete
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody SysUser sysUser){
        userService.update(Wrappers.lambdaUpdate(SysUser.class)
                .eq(SysUser::getId,sysUser.getId())
                .set(SysUser::getDelFlag,2)
        );
       return   Result.OK();
    }


}

postman测试

MybatisPlus-删除_第2张图片

3.彻底删除数据库记录

(11)controller

package com.lpc.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lpc.common.Result;
import com.lpc.entity.SysUser;
import com.lpc.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author lpc
 * @Date 2024 01 11 14 23
 **/
@RequestMapping("/lpc/user")
@RequiredArgsConstructor
@RestController
public class SysUserController {
    private final SysUserService userService;

    
    /**
     * 彻底删除记录
     * 路径:localhost:8888/lpc/user/delete2
     */
    @PostMapping("/delete2")
    public Result delete2(Integer id){
        userService.removeById(id);
        return Result.OK();
    }


}

postman

MybatisPlus-删除_第3张图片

MybatisPlus-删除_第4张图片

MybatisPlus-删除_第5张图片

你可能感兴趣的:(#,Mybatis-plus框架,java,数据库,spring,boot,maven,idea)