1. 程式人生 > >初次詳細搭建SpringBoot+Mybatis+mysql+swagger+Lombok實現增刪改查的功能DOM

初次詳細搭建SpringBoot+Mybatis+mysql+swagger+Lombok實現增刪改查的功能DOM

話不多說直接進入正題,就是這麼果斷與風騷。

下載安裝外掛

在搭建專案前需要準備些前提工作,方便咱們後續搭建專案。需要下載安裝和配置gradle及swagger所需要的檔案。

下載配置環境變數gradle

  1. 安裝JDK8(必須是JDK或JRE7以上,使用java -version檢視當前電腦java版本),並配置JAVA_HOME環境變數。首先準備下jdk 是否安裝了。注意版本哦
  2. 解壓。如果你下載的是gradle-xx-all.zip的完整包,解壓在本地盤中D:\gradle\gradle-4.8
  3. 配置環境變數 配置環境變數:GRADLE_HOME,指定gradle解壓路徑。 在這裡插入圖片描述 找到path新增:%GRADLE_HOME%\bin; 在這裡插入圖片描述 在命令視窗輸入”gradle -v“,進行驗證,出現以下提示則表示成功 在這裡插入圖片描述

搭建專案及配置相應的配置

基於上面咱們安裝和配置的gradle,下面咱們可以開始使用gradle來搭建咱們的專案。

建立專案基本的專案結構

使用gradle搭建SpringBoot+MyBatis。

使用Spring Initializr新建一個專案,在idea中選擇File→New→Project 在這裡插入圖片描述 選擇Spring Initializr 在這裡插入圖片描述 Group(專案包路徑)和Artifact(包名)你隨便填,Type選Gradle Project,Packaging選jar,然後點下一步 在這裡插入圖片描述 分別在Web下面選擇Web,SQL下面選擇MyBatis、MySQL,選擇後的依賴會出現在最右邊,如圖所示,我就選擇了這三個: 在這裡插入圖片描述

確認gradle路徑是否正確 在這裡插入圖片描述 點選上面Ok進入畫面,到此我們使用gradle搭建SpringBoot+MyBatis完成 在這裡插入圖片描述 下面咱們開始建立專案的目錄結構及檔案 在這裡插入圖片描述

安裝和配置lombok外掛

安裝lombok外掛

在這裡插入圖片描述 在這裡插入圖片描述 在下載過程過因為網路原因有可能需要重複點選下載 在這裡插入圖片描述 在這裡插入圖片描述 下載完成後需要配置下註解處理器 在這裡插入圖片描述

在build.gradle檔案中配置lombok

compileOnly(“org.projectlombok:lombok:1.16.16”) 在這裡插入圖片描述

swagger概述

Swagger 是一個幫助完善專案文件規範的框架。我們在類上使用提供的註解寫註釋,swagger可以根據我們寫的註釋內容生成相應的web頁面,展示我們專案中的api文件。同時我們可以直接在頁面上直接呼叫相應的介面。

下載配置swagger

  1. 在GitHub 地址:https://github.com/swagger-api/swagger-ui 上下載SwaggerUI專案,將dist下所有內容拷貝到本地專案server-api/webapp下面,結果目錄如下圖所示: 在這裡插入圖片描述
  2. 在專案工程下建立webapp資料夾放入到swagger下,修改index.html檔案將url: "https://petstore.swagger.io/v2/swagger.json"替換為url: “/v2/api-docs” 在這裡插入圖片描述 在這裡插入圖片描述
  3. 新增swagger依賴,修改build.gradle檔案 compile(‘io.springfox:springfox-swagger2:2.8.0’) compile(‘io.springfox:springfox-swagger-ui:2.8.0’) compile(‘io.swagger:swagger-jersey2-jaxrs:1.5.8’) compile(‘com.mangofactory:swagger-springmvc:1.0.2’) compile(‘com.mangofactory:swagger-models:1.0.2’) compile(‘com.wordnik:swagger-annotations:1.3.11’)

搭建整體專案程式碼

在config下建立SwaggerConfig.java

package com.springboot.demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //com.springboot.demo.controlle所需要掃描的包地址
                .apis(RequestHandlerSelectors.basePackage("com.springboot.demo.controlle"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用者DOM服務API")//大標題
                .description("阿飛提供的user API")//詳細描述
                .version("1.0")//版本
                .termsOfServiceUrl("www.baidu.com")
                .contact(new Contact("阿飛","www.baidu.com", "[email protected]"))//作者
                .build();
    }
}

在config下建立SwaggerConfig.java

package com.springboot.demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //com.springboot.demo.controlle所需要掃描的包地址
                .apis(RequestHandlerSelectors.basePackage("com.springboot.demo.controlle"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用者DOM服務API")//大標題
                .description("阿飛提供的user API")//詳細描述
                .version("1.0")//版本
                .termsOfServiceUrl("www.baidu.com")
                .contact(new Contact("阿飛","www.baidu.com", "[email protected]"))//作者
                .build();
    }
}

在controlle下建立UserController.java

package com.springboot.demo.controlle;

import com.springboot.demo.entity.UserEntity;
import com.springboot.demo.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/user")
@Api(tags = "使用者資訊管理介面")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "獲取所有使用者資訊")
    @GetMapping
    public List<UserEntity> queryList(){
        return userService.queryList();
    }

    @ApiOperation(value = "通過使用者id獲取使用者資訊", notes = "通過使用者id獲取使用者資訊")
    @GetMapping("/{id}")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "id", paramType = "path", value = "使用者ID")})
    public UserEntity queryUserEntity(@PathVariable Integer id){
        UserEntity userEntity=userService.findById(id);
        return userEntity;
    }

    @ApiOperation(value = "新增使用者資訊", notes = "新增使用者資訊")
    @PostMapping
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userName", paramType = "path", value = "使用者姓名"),
            @ApiImplicitParam(name = "userSex", paramType = "path", value = "使用者性別"),
            @ApiImplicitParam(name = "userAge", paramType = "path", value = "使用者年齡")
    })
    public String add(@Valid @RequestBody UserEntity userEntity) {
        userService.insertEntity(userEntity);
        return "新增成功";
    }

    /**
     * 更新使用者,根據id去更新
     */
    //input輸入引數
    @ApiOperation(value = "通過id修改使用者", notes = "通過id修改使用者")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者ID", required = true, dataType="long", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "使用者姓名", dataType="string", paramType = "query"),
            @ApiImplicitParam(name = "userSex", value = "使用者性別", dataType="string", paramType = "query"),
            @ApiImplicitParam(name = "userAge", value = "使用者年齡", dataType="string", paramType = "query")
    })
    public String update(UserEntity userEntity) {
        userService.updateEntity(userEntity);
        return "修改成功";
    }
    
    @ApiOperation(value = "通過id刪除使用者", notes = "通過id刪除使用者")
    @DeleteMapping("/{id}")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", paramType = "path", value = "使用者ID")})
    public String delete(@PathVariable Integer id) {
        userService.deleteEntity(id);
        return "刪除成功";
    }
}

在entity下建立UserEntity.java

package com.springboot.demo.entity;

import lombok.Data;

@Data
public class UserEntity {
    private int id;
    private String userName;
    private String userSex;
    private String userAge;
}

在mapper下建立UserMapper.java

package com.springboot.demo.mapper;

import com.springboot.demo.entity.UserEntity;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

public interface UserMapper {
    @Select("select ID,USER_ANEM,USER_SEX,USER_AGE from testUser")
    @Results({
            @Result(property = "id", column = "ID"),
            @Result(property = "userName", column = "USER_ANEM"),
            @Result(property = "userSex", column = "USER_SEX"),
            @Result(property = "userAge", column = "USER_AGE")})
    List<UserEntity> queryList();

    @Select("SELECT ID,USER_ANEM,USER_SEX,USER_AGE FROM testUser WHERE ID = #{id}")
    @Results({
            @Result(property = "id", column = "ID"),
            @Result(property = "userName", column = "USER_ANEM"),
            @Result(property = "userSex", column = "USER_SEX"),
            @Result(property = "userAge", column = "USER_AGE")})
    UserEntity findById(long id);

    @Insert("INSERT INTO testUser(USER_ANEM, USER_SEX) VALUES(#{userName}, #{userSex})")
    int insertParam(@Param("USER_ANEM") String userName, @Param("USER_SEX") String userSex);

    @Insert("INSERT INTO testUser(USER_ANEM, USER_SEX) VALUES(#{userName,jdbcType=VARCHAR}, #{userSex,jdbcType=VARCHAR})")
    int insertByMap(Map<String, Object> map);

    @Insert("insert into testUser(USER_ANEM,USER_SEX,USER_AGE) values(#{userName,jdbcType=VARCHAR},#{userSex,jdbcType=VARCHAR},#{userAge,jdbcType=VARCHAR})")
    int insertEntity(UserEntity entity);

    @Update("UPDATE testUser SET USER_ANEM=#{userName,jdbcType=VARCHAR},USER_SEX=#{userSex,jdbcType=VARCHAR},USER_AGE=#{userAge,jdbcType=VARCHAR} WHERE ID=#{id}")
    int updateEntity(UserEntity user);

    @Delete("DELETE FROM testUser WHERE ID =#{id}")
    int remove(Integer id);

    @Delete("DELETE FROM testUser WHERE ID =#{id}")
    int deleteEntity(UserEntity entity);
}

在service下建立UserService.java

package com.springboot.demo.service;

import com.springboot.demo.entity.UserEntity;
import com.springboot.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired(required = false)
    private UserMapper mapper;

    public List<UserEntity> queryList() {
        List<UserEntity> userList = mapper.queryList();
        return userList;
    }

    public UserEntity findById(long id) {
        return mapper.findById(id);
    }

    public int insertEntity(UserEntity userEntity) {
        return mapper.insertEntity(userEntity);
    }

    public int insertParam() {
        return mapper.insertParam("阿飛","男");
    }

    public int insertByMap() {
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("userNaeme","zhaotong");
        map.put("userSex","男");
        return mapper.insertByMap(map);
    }

    public int updateEntity(UserEntity userEntity) {
        return mapper.updateEntity(userEntity);
    }

    public int deleteEntity(Integer id) {
        return mapper.remove(id);
    }
}

啟動類DemoApplication.java

package com.springboot.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@MapperScan("com.springboot.*")
@EnableSwagger2
@ServletComponentScan
public class DemoApplication {

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

resources檔案下application.yml

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/testDB?useUnicode=true&characterEncoding=utf8
    username: root
    password: xxxxx
swagger:
  basePackage: com.kingboy.controller
  title: 使用者服務
  description: 使用者基本增刪改查
  version: V1.0

build.gradle檔案所需要包配置

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
    runtimeOnly('mysql:mysql-connector-java')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
    compileOnly("org.projectlombok:lombok:1.16.16")
    compile('io.springfox:springfox-swagger2:2.8.0')
    compile('io.springfox:springfox-swagger-ui:2.8.0')
    compile('io.swagger:swagger-jersey2-jaxrs:1.5.8')
    compile('com.mangofactory:swagger-springmvc:1.0.2')
    compile('com.mangofactory:swagger-models:1.0.2')
    compile('com.wordnik:swagger-annotations:1.3.11')
}