基于springboot实现增删改查

基于springboot实现增删改查

    • 一、数据库搭建
    • 二、后端环境准备
      • 1、新建项目
      • 2、基本配置
      • 3、实现增删改查

一、数据库搭建

CREATE TABLE `attack_point` (
 `ap_id` int(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
 `ap_name` varchar(50) NOT NULL,
 PRIMARY KEY (`ap_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

基于springboot实现增删改查_第1张图片
下面我们就对这个表格进行增删改查。

二、后端环境准备

1、新建项目

(1)新建maven项目,选择next:(jdk版本为1.8)
基于springboot实现增删改查_第2张图片
(2)为项目命名:
基于springboot实现增删改查_第3张图片

(3)配置maven
基于springboot实现增删改查_第4张图片

(4)设置编码格式:
基于springboot实现增删改查_第5张图片

2、基本配置

(1)删除src目录,然后pom文件如下:



    4.0.0

    org.hisi.kirin
    attack_pattern_database
    1.0-SNAPSHOT
    
        attack_common
        attack_model
        attack_utils
        attack_ssm
    
    pom

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
    
    
        
        UTF-8
        UTF-8
        
        1.8
        1.8

        
        2.1.5.RELEASE
        2.6
        1.12
        1.18.8
        5.1.46
        3.5.1
        2.0.1
        3.1.1
        3.5
        1.2.3
        1.10.2
        0.9.1
        1.2.58
        2.9.9
        1.0.9.RELEASE
        2.1.6
        Greenwich.RELEASE
        4.2.0
        portable-1.3.4
        1.26.5
        4.11.1
        4.12
        6.3.1
        7.2.0
        4.1.1
        3.4.1
        2.2.7.RELEASE
        2.0.1
        0.9.11
        2.9.2
        2.0.2
        2.1.0.RELEASE
        2.2.0-SNAPSHOT
    
    
        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        
        
        
            org.projectlombok
            lombok
            ${lombok.version}
            provided
        
    
    

        
            
            
                heima-leadnews-apis
                com.heima
                ${project.version}
            
            
                heima-leadnews-common
                com.heima
                ${project.version}
            
            
                heima-leadnews-model
                com.heima
                ${project.version}
            
            
                heima-leadnews-utils
                com.heima
                ${project.version}
            
            
            
                org.springframework.security
                spring-security-jwt
                ${spring.jwt.version}
            
            
                org.reflections
                reflections
                ${reflections.version}
            
            
                org.springframework.boot
                spring-boot-starter-web
                
                
                    
                        org.springframework.boot
                        spring-boot-starter-logging
                    
                    
                        org.slf4j
                        slf4j-log4j12
                    
                
                ${spring.boot.version}
            
            
                org.springframework.boot
                spring-boot-starter
                
                    
                        org.springframework.boot
                        spring-boot-starter-logging
                    
                    
                        org.slf4j
                        slf4j-log4j12
                    
                
                ${spring.boot.version}
            
            
            
                commons-io
                commons-io
                ${commons.io.version}
            
            
                org.apache.commons
                commons-lang3
                ${lang3.version}
            
            
            
                commons-codec
                commons-codec
                ${commons.codec.version}
            
            
            
                mysql
                mysql-connector-java
                ${mysql.version}
            
            
                org.mybatis
                mybatis
                ${mybatis.version}
            
            
                org.mybatis
                mybatis-spring
                ${mybatis.spring.version}
            
            
                com.github.pagehelper
                pagehelper-spring-boot-starter
                ${pagehelper.version}
            
            
            
                org.jsoup
                jsoup
                ${jsoup.version}
            
            
            
                io.jsonwebtoken
                jjwt
                ${jwt.version}
            
            
            
                com.alibaba
                fastjson
                ${fastjson.version}
            
            
                com.fasterxml.jackson.dataformat
                jackson-dataformat-cbor
                ${fastjson.dataformat.version}
            
            
                com.fasterxml.jackson.dataformat
                jackson-dataformat-xml
                ${fastjson.dataformat.version}
            
            
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring.cloud.version}
                pom
                import
            
            
            
                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                ${com.alibaba.cloud}
                pom
                import
            
            
            
                de.codecentric
                spring-boot-admin-dependencies
                ${spring.boot.admin.version}
                pom
                import
            
            
            
                org.apache.curator
                curator-framework
                ${curator.version}
            
            
                org.apache.curator
                curator-recipes
                ${curator.version}
            
            
            
                com.hankcs
                hanlp
                ${hanlp.version}
            
            
            
                com.github.tobato
                fastdfs-client
                ${fastdfs.version}
            
            
                com.aliyun
                aliyun-java-sdk-core
                ${ali.core.version}
            
            
                com.aliyun
                aliyun-java-sdk-green
                ${ali.green.version}
            
            
            
                junit
                junit
                ${junit.version}
            
            
            
                io.searchbox
                jest
                ${searchbox.version}
            
            
                org.elasticsearch
                elasticsearch
                ${elasticsearch.version}
            
            
            
                org.springframework.kafka
                spring-kafka
                ${kafka.version}
            
            
                org.apache.kafka
                kafka-streams
                ${kafka.client.version}
                
                    
                        connect-json
                        org.apache.kafka
                    
                
            

            
                org.apache.kafka
                kafka-clients
                ${kafka.client.version}
            
            
                com.github.xiaoymin
                knife4j-spring-boot-starter
                ${knife4j.version}
            
            
                io.springfox
                springfox-swagger2
                ${swagger.version}
            
            
                io.springfox
                springfox-swagger-ui
                ${swagger.version}
            
            
                com.baomidou
                mybatis-plus-boot-starter
                ${mybatis.plus.version}
            
            
            
                com.xuxueli
                xxl-job-core
                ${xxl.job.version}
            
        
    

    
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                    
                        
                            
                                repackage
                            
                        
                    
                
            
        
        
            
                maven-resources-plugin
                
                    true
                
            

            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.7.0
                
                    ${java.version}
                    ${java.version}
                
            
        
        
            
                src/main/resources
                
                    **/*.*
                
                true
            
        
        
            
                src/test/resources
                true
            
        
    

    
        
            dev
            
                
                    maven_dev.properties
                
            
        
        
            test
            
                true
            
            
                
                    maven_test.properties
                
            
        
        
            prod
            
                
                    maven_prod.properties
                
            
        
    


(2)新建3个子模块:attack_common、attack_model和attack_utils
其中attack_common模块如下:
基于springboot实现增删改查_第6张图片
(i)pom文件:



    
        attack_pattern_database
        org.hisi.kirin
        1.0-SNAPSHOT
    
    4.0.0

    attack_common
    jar

    
        8
        8
    

    
        
            org.hisi.kirin
            attack_utils
            1.0-SNAPSHOT
        
        
            org.reflections
            reflections
        
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-quartz
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-test
        
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.apache.commons
            commons-pool2
        
        
            org.springframework.boot
            spring-boot-starter-cache
        
        
            org.apache.commons
            commons-lang3
        
        
            org.projectlombok
            lombok
            provided
        
        
        
            com.github.tobato
            fastdfs-client
        
        
        
            org.springframework.kafka
            spring-kafka
        
        
            org.apache.kafka
            kafka-clients
        
        
        
            org.apache.kafka
            kafka-streams
        

        
            org.quartz-scheduler
            quartz
            2.3.1
        
        
            com.aliyun
            aliyun-java-sdk-core
        
        
            com.aliyun
            aliyun-java-sdk-green
        
        
        
            org.apache.hbase
            hbase-client
            2.1.5
            
                
                    org.slf4j
                    slf4j-api
                
                
                    log4j
                    log4j
                
                
                    junit
                    junit
                
                
                    slf4j-log4j12
                    org.slf4j
                
            
        
        
            junit
            junit
        
        
            org.jsoup
            jsoup
        
        
            com.xuxueli
            xxl-job-core
        

        
        
            joda-time
            joda-time
            2.10.5
        

        
            com.github.xiaoymin
            knife4j-spring-boot-starter
        

    


(ii)Swagger2Configuration.java

package com.hisi.kirin.common.knife4j;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Configuration {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //分组名称
                .groupName("1.0")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.hisi.kirin"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("攻击模式库API文档")
                .description("攻击模式库API文档")
                .version("1.0")
                .build();
    }
}

(iii)application.yml

#全局端口定义server:
# 全局字符集设置
spring:
http:
 encoding:
  force: true
  charset: utf-8
  enabled: true
aop:
 proxy-target-class: true
server:
tomcat:
 uri-encoding: utf-8

(iv)多环境切换:
maven_dev.properties:

profiles.name=dev

maven_prod.properties

profiles.name=prod

maven_test.properties

profiles.name=test

其他模块的多环境切换如上。
attack_model模块如下:
基于springboot实现增删改查_第7张图片
(i)pom文件:



    
        attack_pattern_database
        org.hisi.kirin
        1.0-SNAPSHOT
    
    4.0.0

    attack_model
    jar

    
        8
        8
    

    
        
            mysql
            mysql-connector-java
        
        
            org.mybatis
            mybatis
        
        
            org.apache.commons
            commons-lang3
        
        
            com.baomidou
            mybatis-plus-boot-starter
        

        
            com.alibaba
            fastjson
        
        io.springfox
        springfox-swagger2
    
        
            io.springfox
            springfox-swagger-ui
        
    


(ii)attack_point实体类和dto类:

package com.hisi.kirin.model.attack_point.dtos;

import com.hisi.kirin.model.common.dtos.PageRequestDto;
import lombok.Data;

@Data
public class AttackPointDto extends PageRequestDto {

    private String apName;
}
package com.hisi.kirin.model.attack_point.pojos;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.io.Serializable;

@Data
@TableName("attack_point")
public class AttackPoint implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "ap_id", type = IdType.AUTO)
    private int apId;
    @TableField("ap_name")
    private String apName;
}

(iii)通用结果相应类:

package com.hisi.kirin.model.common.dtos;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@ApiModel
public class PageRequestDto {

    @ApiModelProperty(value = "每页显示条数")
    protected Integer size;
    @ApiModelProperty(value = "当前第几页")
    protected Integer page;

    public void checkParam() {
        if (this.page == null || this.page < 0) {
            setPage(1);
        }
        if (this.size == null || this.size < 0 || this.size > 100) {
            setSize(10);
        }
    }
}
package com.hisi.kirin.model.common.dtos;

import java.io.Serializable;

public class PageResponseResult extends ResponseResult implements Serializable {
    private Integer currentPage;
    private Integer size;
    private Integer total;

    public PageResponseResult(Integer currentPage, Integer size, Integer total) {
        this.currentPage = currentPage;
        this.size = size;
        this.total = total;
    }

    public PageResponseResult() {

    }


    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}
package com.hisi.kirin.model.common.dtos;

import com.alibaba.fastjson.JSON;
import com.hisi.kirin.model.common.enums.AppHttpCodeEnum;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用的结果返回类
 * @param 
 */
public class ResponseResult<T> implements Serializable {

    private String host;

    private Integer code;

    private String errorMessage;

    private T data;

    public ResponseResult() {
        this.code = 200;
    }

    public ResponseResult(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    public ResponseResult(Integer code, String msg, T data) {
        this.code = code;
        this.errorMessage = msg;
        this.data = data;
    }

    public ResponseResult(Integer code, String msg) {
        this.code = code;
        this.errorMessage = msg;
    }

    public static ResponseResult errorResult(int code, String msg) {
        ResponseResult result = new ResponseResult();
        return result.error(code, msg);
    }

    public static ResponseResult okResult(int code, String msg) {
        ResponseResult result = new ResponseResult();
        return result.ok(code, null, msg);
    }

    public static ResponseResult okResult(Object data) {
        ResponseResult result = setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        if(data!=null) {
            result.setData(data);
        }
        return result;
    }

    public static ResponseResult errorResult(AppHttpCodeEnum enums){
        return setAppHttpCodeEnum(enums,enums.getErrorMessage());
    }

    public static ResponseResult errorResult(AppHttpCodeEnum enums, String errorMessage){
        return setAppHttpCodeEnum(enums,errorMessage);
    }

    public static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums){
        return okResult(enums.getCode(),enums.getErrorMessage());
    }

    private static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums, String errorMessage){
        return okResult(enums.getCode(),errorMessage);
    }

    public ResponseResult<?> error(Integer code, String msg) {
        this.code = code;
        this.errorMessage = msg;
        return this;
    }

    public ResponseResult<?> ok(Integer code, T data) {
        this.code = code;
        this.data = data;
        return this;
    }

    public ResponseResult<?> ok(Integer code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.errorMessage = msg;
        return this;
    }

    public ResponseResult<?> ok(T data) {
        this.data = data;
        return this;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }


    public static void main(String[] args) {
        //前置
        /*AppHttpCodeEnum success = AppHttpCodeEnum.SUCCESS;
        System.out.println(success.getCode());
        System.out.println(success.getErrorMessage());*/

        //查询一个对象
        /*Map map = new HashMap();
        map.put("name","zhangsan");
        map.put("age",18);
        ResponseResult result = ResponseResult.okResult(map);
        System.out.println(JSON.toJSONString(result));*/


        //新增,修改,删除  在项目中统一返回成功即可
       /* ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
        System.out.println(JSON.toJSONString(result));*/


        //根据不用的业务返回不同的提示信息  比如:当前操作需要登录、参数错误
        /*ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        System.out.println(JSON.toJSONString(result));*/

        //查询分页信息
        PageResponseResult responseResult = new PageResponseResult(1,5,50);
        List list = new ArrayList();
        list.add("itcast");
        list.add("itheima");
        responseResult.setData(list);
        System.out.println(JSON.toJSONString(responseResult));
    }
}

(iv)枚举类

package com.hisi.kirin.model.common.enums;

public enum AppHttpCodeEnum {

    // 成功段0
    SUCCESS(0,"操作成功"),
    // 登录段1~50
    NEED_LOGIN(1,"需要登录后操作"),
    LOGIN_PASSWORD_ERROR(2,"密码错误"),
    // TOKEN50~100
    TOKEN_INVALID(50,"无效的TOKEN"),
    TOKEN_EXPIRE(51,"TOKEN已过期"),
    TOKEN_REQUIRE(52,"TOKEN是必须的"),
    // SIGN验签 100~120
    SIGN_INVALID(100,"无效的SIGN"),
    SIG_TIMEOUT(101,"SIGN已过期"),
    // 参数错误 500~1000
    PARAM_REQUIRE(500,"缺少参数"),
    PARAM_INVALID(501,"无效参数"),
    PARAM_IMAGE_FORMAT_ERROR(502,"图片格式有误"),
    SERVER_ERROR(503,"服务器内部错误"),
    // 数据错误 1000~2000
    DATA_EXIST(1000,"数据已经存在"),
    AP_USER_DATA_NOT_EXIST(1001,"ApUser数据不存在"),
    DATA_NOT_EXIST(1002,"数据不存在"),
    // 数据错误 3000~3500
    NO_OPERATOR_AUTH(3000,"无权限操作"),
    NEED_ADMIND(3001,"需要管理员权限");

    int code;
    String errorMessage;

    AppHttpCodeEnum(int code, String errorMessage){
        this.code = code;
        this.errorMessage = errorMessage;
    }

    public int getCode() {
        return code;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}

attack_utils模块结构如下:
基于springboot实现增删改查_第8张图片
(i)pom文件如下:



    
        attack_pattern_database
        org.hisi.kirin
        1.0-SNAPSHOT
    
    4.0.0

    attack_utils
    jar

    
        8
        8
    

    
        
            org.hisi.kirin
            attack_model
            1.0-SNAPSHOT
        
        
            commons-codec
            commons-codec
        
        
            com.alibaba
            fastjson
        
        
            io.jsonwebtoken
            jjwt
        
        
        
            com.hankcs
            hanlp
        
        
            org.apache.commons
            commons-lang3
        
        
            org.jsoup
            jsoup
        
        
            commons-beanutils
            commons-beanutils
            1.9.3
        
        
        
            org.apache.poi
            poi
            3.14
        
        
            org.apache.poi
            poi-ooxml
            3.14
        
    


3、实现增删改查

新建模块attack_ssm:
结构如下:
基于springboot实现增删改查_第9张图片

pom文件:



    
        attack_pattern_database
        org.hisi.kirin
        1.0-SNAPSHOT
    
    4.0.0

    attack_ssm

    
        8
        8
    

    
        
        
            org.hisi.kirin
            attack_model
            1.0-SNAPSHOT
        
        
            org.hisi.kirin
            attack_common
            1.0-SNAPSHOT
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    


config配置:

package com.hisi.kirin.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.hisi.kirin.common.knife4j")
public class KnifeConfig {
}

mapper层:

package com.hisi.kirin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hisi.kirin.model.attack_point.pojos.AttackPoint;

public interface AttackPointMapper extends BaseMapper<AttackPoint> {
}

service层:

package com.hisi.kirin.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.hisi.kirin.model.attack_point.dtos.AttackPointDto;
import com.hisi.kirin.model.attack_point.pojos.AttackPoint;
import com.hisi.kirin.model.common.dtos.ResponseResult;

public interface AttackPointService extends IService<AttackPoint> {

    /**
     * 根据名称分页查询攻击点列表
     * @param dto
     * @return
     */
    public ResponseResult findByNameAndPage(AttackPointDto dto);

    /**
     * 新增
     * @param attackPoint
     * @return
     */
    public ResponseResult insert(AttackPoint attackPoint);

    /**
     * 修改
     * @param attackPoint
     * @return
     */
    public ResponseResult update(AttackPoint attackPoint);

    /**
     * 删除
     * @param id
     * @return
     */
    public ResponseResult deleteById(Integer id);

}

impl层:

package com.hisi.kirin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hisi.kirin.mapper.AttackPointMapper;
import com.hisi.kirin.model.attack_point.dtos.AttackPointDto;
import com.hisi.kirin.model.attack_point.pojos.AttackPoint;
import com.hisi.kirin.model.common.dtos.PageResponseResult;
import com.hisi.kirin.model.common.dtos.ResponseResult;
import com.hisi.kirin.model.common.enums.AppHttpCodeEnum;
import com.hisi.kirin.service.AttackPointService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class AttackPointServiceImpl extends ServiceImpl<AttackPointMapper, AttackPoint> implements AttackPointService {

    @Override
    public ResponseResult findByNameAndPage(AttackPointDto dto) {
        //1.参数检测
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        //2.安装名称模糊分页查询
        Page page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<AttackPoint> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(dto.getApName())){
            lambdaQueryWrapper.like(AttackPoint::getApName,dto.getApName());
        }
        IPage result = page(page, lambdaQueryWrapper);

        //3.结果封装
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult insert(AttackPoint attackPoint) {
        //1.检查参数
        if(null == attackPoint){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存
        save(attackPoint);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult update(AttackPoint attackPoint) {
        //1.检查参数
        if(null == attackPoint || attackPoint.getApId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.修改
        updateById(attackPoint);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断当前频道是否存在 和 是否有效
        AttackPoint attackPoint = getById(id);
        if(attackPoint==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"频道信息不存在");
        }

        //3.删除频道
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}

controller层:

package com.hisi.kirin.controller;

import com.hisi.kirin.model.attack_point.dtos.AttackPointDto;
import com.hisi.kirin.model.attack_point.pojos.AttackPoint;
import com.hisi.kirin.model.common.dtos.ResponseResult;
import com.hisi.kirin.service.AttackPointService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ap")
@Api(tags = "攻击点管理")
public class AttackPointController {

    @Autowired
    private AttackPointService attackPointService;

    @ApiOperation("根据名称查询攻击点列表")
    @PostMapping("/list")
    public ResponseResult findByNameAndPage(@RequestBody AttackPointDto dto){
        return attackPointService.findByNameAndPage(dto);
    }

    @ApiOperation("新增攻击点")
    @PostMapping("/save")
    public ResponseResult save(@RequestBody AttackPoint attackPoint) {
        return attackPointService.insert(attackPoint);
    }

    @ApiOperation("更新攻击点")
    @PostMapping("/update")
    public ResponseResult update(@RequestBody AttackPoint attackPoint) {
        return attackPointService.update(attackPoint);
    }

    @ApiOperation("根据id删除攻击点")
    @GetMapping("/del/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer id) {
        return attackPointService.deleteById(id);
    }
}

启动类:

package com.hisi.kirin;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@MapperScan("com.hisi.kirin.mapper")
public class AttackPointApplication {

    public static void main(String[] args) {
        SpringApplication.run(AttackPointApplication.class,args);
    }

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

application.yml

server:
  port: 9001
spring:
  application:
    name: attack-point
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/secguard?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
# 设置Mapper接口所对应的XML文件位置,如果你在Mapper接口中有自定义方法,需要进行该配置
mybatis-plus:
  mapper-locations: classpath*:mapper/*.xml
  # 设置别名包扫描路径,通过该属性可以给包中的类注册别名
  type-aliases-package: com.hisi.kirin

logging.level.org.springframework.boot.autoconfigure: error

logback.xml


<configuration>
    
    <property name="LOG_HOME" value="d:/logs"/>

    
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
            <charset>utf8charset>
        encoder>
    appender>

    
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            
            <fileNamePattern>${LOG_HOME}/leadnews.%d{yyyy-MM-dd}.logfileNamePattern>
        rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>

    
    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        
        <discardingThreshold>0discardingThreshold>
        
        <queueSize>512queueSize>
        
        <appender-ref ref="FILE"/>
    appender>


    <logger name="org.apache.ibatis.cache.decorators.LoggingCache" level="DEBUG" additivity="false">
        <appender-ref ref="CONSOLE"/>
    logger>
    <logger name="org.springframework.boot" level="debug"/>
    <root level="info">
        
        <appender-ref ref="FILE"/>
        <appender-ref ref="CONSOLE"/>
    root>
configuration>

测试路径:
http://localhost:9001/doc.html

相关文章:
https://blog.csdn.net/caopeng721210/article/details/107318887?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162653901016780274187747%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162653901016780274187747&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-2-107318887.first_rank_v2_pc_rank_v29&utm_term=Positive+matches%3A&spm=1018.2226.3001.4187

你可能感兴趣的:(基于springboot实现增删改查)