SpringBoot+MyBatisPlus+Vue 前後端分離項目快速搭建過程(後端)

數據庫準備

data_test.sql:

/*
SQLyog Enterprise v12.08 (64 bit)
MySQL - 5.7.31 : Database - data_test
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`data_test` /*!40100 DEFAULT CHARACTER SET utf8  */;

USE `data_test`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) CHARACTER SET utf8  NOT NULL COMMENT '賬號',
  `password` varchar(50) CHARACTER SET utf8  NOT NULL COMMENT '密碼',
  `user_state` varchar(10) CHARACTER SET utf8  NOT NULL DEFAULT '1' COMMENT '狀態,邏輯刪除',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

/*Data for the table `user` */

LOCK TABLES `user` WRITE;

insert  into `user`(`user_id`,`user_name`,`password`,`user_state`) values (1,'keafmd','keafmd','1'),(3,'21312321','123','0'),(11,'213','213','1'),(12,'keafmd','666','0');

UNLOCK TABLES;

/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40111 SET [email protected]_SQL_NOTES */;

後端搭建

1、快速創建個SpringBoot項目

第一步:Spring Initializr

在這裡插入圖片描述

第二步:Spring Initializr Project Settings

在這裡插入圖片描述

第三步:添加個Lombok工具

在這裡插入圖片描述

第四步:Finish

在這裡插入圖片描述

初始化的樣子:

在這裡插入圖片描述

2、引入依賴

此處貼上整個pom.xml,部分依賴可能對於簡單需求而言是多餘的,可以自行舍棄。

pom.xml代碼:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.keafmd</groupId>
    <artifactId>springboot-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-server</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>


        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>io.github.yedaxia</groupId>
            <artifactId>japidocs</artifactId>
            <version>1.4.3</version>
            <scope>test</scope>

        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>


        <!-- 解密程序 https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on -->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.68</version>
        </dependency>

        <!--JWT 依賴 -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3、編寫代碼快速生成代碼

因為此代碼為輔助代碼,放在test包下即可,相關的數據庫信息以及包信息需要和你們自己的保持一致,自行修改,如何包命名和我一致,隻需要修改數據庫相關信息即可。

CodeGenerator:

package com.keafmd.mp;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Keafmd
 *
 * @ClassName: CodeGenerator
 * @Description: 代碼生成器
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 17:06
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class CodeGenerator {

    /**
     * <p>
     * 讀取控制臺內容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請輸入正確的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
//        System.out.println("projectPath = " + projectPath);
        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setOutputDir("D:\\test");
        gc.setAuthor("關註公眾號:牛哄哄的柯南");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實體屬性 Swagger2 註解
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/data_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("18044229");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.keafmd");
        mpg.setPackageInfo(pc);

        // 自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定義輸出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定義配置會被優先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設置瞭前後綴、此處註意 xml 的名稱會跟著發生變化!!
                return projectPath + "/src/main/resources/com/keafmd/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("m_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

4、運行代碼生成器生成代碼

在控制臺輸入user(表名)
在這裡插入圖片描述
紅框內為自動生成的代碼:
在這裡插入圖片描述

5、編寫application.properties

個人習慣把application.properties改為application.yml,修改端口為80

server:
  port: 80

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1/data_test?useSSL=false&&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 18044229

  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

6、在啟動類上添加@MapperScan

SpringbootServerApplication:

package com.keafmd;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.keafmd.mapper")
public class SpringbootServerApplication {

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

}

7、編寫測試代碼測試數據庫是否連接正確

1、在 UserMapper代碼頁大括號內,按下Alt+Insert,選擇Test
在這裡插入圖片描述
2、Ok
在這裡插入圖片描述
3、自動生成瞭測試類
在這裡插入圖片描述
4、編寫測試代碼

UserMapperTest :

package com.keafmd.mapper;

import com.keafmd.SpringbootServerApplication;
import com.keafmd.entity.User;
import com.keafmd.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest(classes = SpringbootServerApplication.class)
class UserMapperTest {

    @Resource
    UserService userService;

    @Test
    public void test1(){
        List<User> userList = userService.list();
        for (User user : userList) {
            System.out.println(user);
        }

    }



}

5、測試結果
在這裡插入圖片描述

至此,後端和數據庫連接沒問題。

8、編寫後端的工具類代碼(封裝結果集、日期處理、解決跨域請求)

在這裡插入圖片描述

1、CommonResult

package com.keafmd.common;

import lombok.Getter;

/**
 * Keafmd
 *
 * @ClassName: CommonResult
 * @Description: 封裝結果集
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Getter
public class CommonResult  {
    private Integer code;
    private String message;
    private Object obj;

    private CommonResult(Integer code, String message, Object obj) {
        this.code = code;
        this.message = message;
        this.obj = obj;
    }

    public static CommonResult nohandler() {
        return new CommonResult(ResultCode.NOHANDLER.getCode(), ResultCode.NOHANDLER.getMessage(),null);
    }
    public static CommonResult success(Object data) {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),data);
    }
    public static CommonResult failed() {
        return new CommonResult(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(),null);
    }
    public static CommonResult failed(String message) {
        return new CommonResult(ResultCode.FAILED.getCode(),message,null);
    }
    public static CommonResult notoken() {
        return new CommonResult(ResultCode.NOTOKEN.getCode(), ResultCode.NOTOKEN.getMessage(),null);
    }
    public static CommonResult nopremiss() {
        return new CommonResult(ResultCode.NOPERMISS.getCode(), ResultCode.NOPERMISS.getMessage(),null);
    }
}

2、DateConverter

package com.keafmd.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Keafmd
 *
 * @ClassName: DateConverter
 * @Description: 日期處理
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Configuration
public class DateConverter implements Converter<String, Date> {

    public DateConverter() {
//        System.out.println("初始化........");
    }

    static List<SimpleDateFormat> sdfs = new ArrayList();

    static {
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        sdfs.add(new SimpleDateFormat("yyyy-MM-dd"));
        sdfs.add(new SimpleDateFormat("yyyy/MM/dd"));

    }

    @Override
    public Date convert(String s) {
        SimpleDateFormat sdf = null;
        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)) {
            sdf = sdfs.get(1);
        }
        else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)){
            sdf = sdfs.get(0);
        }
        else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", s)){
            sdf = sdfs.get(3);
        }
        else if (Pattern.matches("^\\d{4}-\\d{2}/-\\d{2}}$", s)){
            sdf = sdfs.get(2);
        }

        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;

    }
}

3、LocalDateTimeConverter

package com.keafmd.common;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Keafmd
 *
 * @ClassName: LocalDateTimeConverter
 * @Description: 日期處理
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Component
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {
    //2021-04-29%2001:02:03
    @Override
    public LocalDateTime convert(String s) {
        return LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}

4、ResultCode

package com.keafmd.common;

import lombok.Getter;

/**
 * Keafmd
 *
 * @ClassName: ResultCode
 * @Description: 結果代碼
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Getter
public enum ResultCode {
    NOHANDLER(404,"請求地址錯誤"),
    SUCCESS(200,"操作成功"),
    FAILED(500,"操作失敗"),
    NOTOKEN(401,"未登錄或登錄已超時"),
    NOPERMISS(403,"無操作權限"),
    ;

    private Integer code;
    private String message;

    ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }



}

5、AppConfig

package com.keafmd.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.keafmd.common.DateConverter;
import com.keafmd.common.LocalDateTimeConverter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: AppConfig
 * @Description: 解決跨域請求
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Configuration
public class AppConfig extends WebMvcConfigurationSupport {

    /**
     * 分頁插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setDialect(new MySqlDialect());
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
    @Bean
    FilterRegistrationBean<CorsFilter> cors(){
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<CorsFilter>();
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://127.0.0.1:81");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        CorsFilter filter = new CorsFilter(source);
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }


    /**
     * curl http://127.0.0.1/user/getById?id=31
     * @param converters
     */

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//        objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //忽略 null 字段

        JavaTimeModule javaTimeModule = new JavaTimeModule();

        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

//        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        objectMapper.registerModule(javaTimeModule);
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
    }

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        super.addFormatters(registry);
        registry.addConverter(new DateConverter());
        registry.addConverter(new LocalDateTimeConverter());
    }
}

6、DefaultExceptionHandler

package com.keafmd.config;

import com.keafmd.common.CommonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/**
 * Keafmd
 *
 * @ClassName: DefaultExceptionHandler
 * @Description:
 * @author: 牛哄哄的柯南
 * @Date: 2021-04-29 18:11
 * @Blog: https://keafmd.blog.csdn.net/
 */

@RestControllerAdvice
public class DefaultExceptionHandler {

    @ExceptionHandler
    public CommonResult exceptionHandler(HttpServletRequest request, Exception ex) {
        ex.printStackTrace();
        if(ex instanceof NoHandlerFoundException) {
            return CommonResult.nohandler();
        }
        return CommonResult.failed(ex.getMessage());
    }


}

9、編寫後端的增刪改查代碼

1、在UserService接口中編寫分頁查詢代碼

package com.keafmd.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服務類
 * </p>
 *
 * @author 關註公眾號:牛哄哄的柯南
 * @since 2021-04-29
 */
public interface UserService extends IService<User> {
    Page pageList(Page page, User user);
}

2、在UserServiceImpl實現類中實現分頁查詢和模糊查找

package com.keafmd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.entity.User;
import com.keafmd.mapper.UserMapper;
import com.keafmd.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服務實現類
 * </p>
 *
 * @author 關註公眾號:牛哄哄的柯南
 * @since 2021-04-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page pageList(Page page, User user) {
        if(page == null){
            page = new Page();
        }

        QueryWrapper wrapper = new QueryWrapper();
        if(user!=null && StringUtils.isNotEmpty(user.getUserName())){
            //根據user_name字段模糊查找
            wrapper.like("user_name",user.getUserName());
        }

        return super.page(page,wrapper);
    }
}

3、在UserController中編寫增刪改查代碼

package com.keafmd.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keafmd.common.CommonResult;
import com.keafmd.entity.User;
import com.keafmd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 關註公眾號:牛哄哄的柯南
 * @since 2021-04-29
 */
@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    UserService userService;

    /**
     * 查找
     * @return
     */
    @RequestMapping("/list")
    CommonResult list(ModelMap modelMap, Page page, @ModelAttribute("user") User user) {

        page = userService.pageList(page, user);
        modelMap.addAttribute("page", page);
        return CommonResult.success(page);
    }

    @RequestMapping("/save")
    CommonResult save(User user){

        return CommonResult.success(userService.saveOrUpdate(user));

    }


    /**
     * 根據id查
     * @param id
     * @return
     */
    @RequestMapping("/getById")
    CommonResult getById(Integer id) {
        return CommonResult.success(userService.getById(id));
    }

    /**
     * 刪除,邏輯刪除
     * @param id
     * @return
     */
    @RequestMapping("/del")
    CommonResult del(Integer id ) {
        User user = userService.getById(id);
        user.setUserState("0");
        return CommonResult.success(userService.updateById(user));
    }


    /**
     * 批量刪除
     * @param id
     * @return
     */
    @RequestMapping("/delByIds")
    CommonResult delByIds(Integer[] id) {
        /*for (Integer integer : id) {
            System.out.println(integer);
        }*/
        return CommonResult.success(userService.removeByIds(Arrays.asList(id)));
    }

}

前端搭建

由於篇幅有限,前端搭建單獨再寫一篇

SpringBoot+MyBatisPlus+Vue 前後端分離項目快速搭建【前端篇】【快速生成後端代碼、封裝結果集、增刪改查、模糊查找】【畢設基礎框架】

以上就是SpringBoot+MyBatisPlus+Vue 前後端分離項目快速搭建【後端篇】【快速生成後端代碼、封裝結果集、增刪改查、模糊查找】【畢設基礎框架】的全部內容

到此這篇關於SpringBoot+MyBatisPlus+Vue 前後端分離項目快速搭建過程(後端)的文章就介紹到這瞭,更多相關SpringBoot+MyBatisPlus+Vue 前後端分離搭建內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!