1. 程式人生 > >[Spring Boot] Spring boot 整合mybatis、postgresql [Gradle構建專案]

[Spring Boot] Spring boot 整合mybatis、postgresql [Gradle構建專案]

[Spring Boot] Spring boot 整合mybatis、postgresql [Gradle構建專案]

[Spring Boot] Spring boot 整合mybatis、postgresql [Gradle構建專案]

依賴關係

下文中libs[“xxx”]的寫法是全域性管理依賴,具體開發時使用以下格式即可

compile(group: 'org.postgresql', name: 'postgresql', version: '42.2.5', ext: 'pom')

build.gradle:

buildscript {
    repositories {
        maven { url = "https://plugins.gradle.org/m2/" }
        maven { url = "http://maven.aliyun.com/nexus/content/groups/public/" }
        jcenter()
    }
    dependencies {
        classpath libs["spring-boot-gradle-plugin"]
    }
}

apply plugin: "idea"
apply plugin: "java"
apply plugin: "maven"
apply plugin: "io.spring.dependency-management"
apply plugin: "org.springframework.boot"

group = "com.example"
version = "1.0.0-SNAPSHOT"
sourceCompatibility = 1.8

dependencies {
    compile "org.springframework.boot:spring-boot-starter-web"

    /*分頁和mapper外掛*/
    compile libs["pagehelper"]
    compile libs["mapper"]

    /**資料庫驅動*/
    compile libs["postgresql"]

    compile libs["mybatis-spring-boot-starter"]

    /*熱部署*/
    compile libs["spring-boot-devtools"]

    /*單元測試*/
    testCompile libs["junit"]
    testCompile "org.springframework.boot:spring-boot-starter-test"
}

核心配置

啟動類

@SpringBootApplication
//開啟事務
@EnableTransactionManagement
//Spring Boot例項掃描
@ComponentScan(basePackages = "com.example")
//Mapper掃描
@MapperScan(basePackages = "com.example.core.**.dao")
public class BootApp {

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

application.yaml檔案

server:
    port: 8080

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    password: postgres
    username: postgres
    url: jdbc:postgresql://127.0.0.1:5433/postgres
  devtools:
      restart:
        enabled: false

#mybatis
mybatis: type-aliases-package: com.example.core.**.model mapper-locations: classpath*:mapper/*.xml

程式碼生成

  • mapper、model採用mybatis-generator-core自動解析資料庫生成
  • gradle構建時src/main/java目錄下的非.java結尾的檔案不會被編譯,所以需要將myabtis對應的xml檔案移至resources目錄,並在application.yaml檔案配置路徑

全域性異常攔截

GlobalExceptionHandler

package com.example.config;

import com.example.common.api.ApiErrorCode;
import com.example.common.api.ApiException;
import com.example.common.api.IErrorCode;
import com.example.common.beans.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

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

/**
 * <p>
 *
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2019年01月11日 10:39
 * @modificationHistory=========================邏輯或功能性重大變更記錄
 * @modify By: {修改人} 2019年01月11日
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * <p>
     * 自定義 REST 業務異常
     * <p>
     *
     * @param e 異常型別
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseJson<Object> handleBadRequest(Exception e) {
        /*
         * 業務邏輯異常
         */
        if (e instanceof ApiException) {
            IErrorCode errorCode = ((ApiException) e).getErrorCode();
            if (null != errorCode) {
                log.debug("Rest request error, {}", errorCode.toString());
                return new ResponseJson().failed(errorCode);
            }
            log.debug("Rest request error, {}", e.getMessage());
            return new ResponseJson().failed(e.getMessage());
        }

        /*
         * 引數校驗異常
         */
        if (e instanceof BindException) {
            BindingResult bindingResult = ((BindException) e).getBindingResult();
            if (null != bindingResult && bindingResult.hasErrors()) {
                List<Object> jsonList = new ArrayList<>();
                bindingResult.getFieldErrors().stream().forEach(fieldError -> {
                    Map<String, Object> jsonObject = new HashMap<>(2);
                    jsonObject.put("name", fieldError.getField());
                    jsonObject.put("msg", fieldError.getDefaultMessage());
                    jsonList.add(jsonObject);
                });
                return new ResponseJson().failed(jsonList, ApiErrorCode.FAILED);
            }
        }

        /**
         * 系統內部異常,列印異常棧
         */
        log.error("Error: handleBadRequest StackTrace : {}", e);
        return new ResponseJson().failed(e.getMessage());
    }
}

ApiErrorCode

package com.example.common.api;

/**
 * <p>
 *  REST API 錯誤碼
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2019年01月11日 10:48
 * @modificationHistory=========================邏輯或功能性重大變更記錄
 * @modify By: {修改人} 2019年01月11日
 * @modify reason: {方法名}:{原因}
 * ...
 */
public enum ApiErrorCode implements IErrorCode {
    /**
     * 失敗
     */
    FAILED("0", "失敗"),
    /**
     * 成功
     */
    SUCCESS("1", "成功");

    private final String code;
    private final String msg;

    ApiErrorCode(final String code, final String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static ApiErrorCode fromCode(String code) {
        ApiErrorCode[] ecs = ApiErrorCode.values();
        for (ApiErrorCode ec : ecs) {
            if (ec.getCode().equalsIgnoreCase(code)) {
                return ec;
            }
        }
        return SUCCESS;
    }

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }

    @Override
    public String toString() {
        return String.format(" ErrorCode:{code=%s, msg=%s} ", code, msg);
    }

}

ApiException

package com.example.common.api;

/**
 * <p>
 *
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2019年01月11日 10:46
 * @modificationHistory=========================邏輯或功能性重大變更記錄
 * @modify By: {修改人} 2019年01月11日
 * @modify reason: {方法名}:{原因}
 * ...
 */
public class ApiException extends RuntimeException {

    /**
     * 錯誤碼
     */
    private IErrorCode errorCode;

    public ApiException(IErrorCode errorCode) {
        super(errorCode.getMsg());
        this.errorCode = errorCode;
    }

    public ApiException(String message) {
        super(message);
    }

    public ApiException(Throwable cause) {
        super(cause);
    }

    public ApiException(String message, Throwable cause) {
        super(message, cause);
    }`在這裡插入程式碼片`

    public IErrorCode getErrorCode() {
        return errorCode;
    }
}

IErrorCode

package com.example.common.api;

/**
 * <p>
 *  REST API 錯誤碼介面
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2019年01月11日 10:46
 * @modificationHistory=========================邏輯或功能性重大變更記錄
 * @modify By: {修改人} 2019年01月11日
 * @modify reason: {方法名}:{原因}
 * ...
 */
public interface IErrorCode {

    /**
     * 錯誤編碼 0、失敗 1、正常
     */
    String getCode();

    /**
     * 錯誤描述
     */
    String getMsg();

}

ResponseJson

package com.example.common.beans;

import com.example.common.api.IErrorCode;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * <p>
 *
 * </p>
 *
 * @author xiachaoyang
 * @version V1.0
 * @date 2018年12月27日 17:26
 * @modificationHistory=========================邏輯或功能性重大變更記錄
 * @modify By: {修改人} 2018年12月27日
 * @modify reason: {方法名}:{原因}
 * ...
 */
@Data
@Accessors(chain = true)
public class ResponseJson<T> {

    private String msg;
    private String code;
    private T data;

    public ResponseJson<T> failed(IErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
        return this;
    }

    public ResponseJson<T> failed(String errorMsg) {
        this.code = "-1";
        this.msg = errorMsg;
        return this;
    }

    public ResponseJson<T> ok(T data) {
        this.data = data;
        this.code = "0";
        this.msg = "success";
        return this;
    }

    public ResponseJson<T> failed(T data, IErrorCode errorCode) {
        this.data = data;
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
        return this;
    }
}

效果(json請求引數中非數字字串無法轉數字錯誤)

在這裡插入圖片描述


更多

掃碼關注或搜尋架構探險之道獲取最新文章,不積跬步無以至千里,堅持每週一更,堅持技術分享^_^