2021-03-14-jwolf-temp-note

2021年3月15日 9点热度 0条评论 来源: jwolf2

 

全局异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = CommonException.class)
    public Object CommonException(CommonException e, HttpServletResponse response) {
        log.error("统一异常处理器捕获【自定义commonException异常】-->" + e.getErrorMsg(), e);
        return ResultEntity.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     *处理spring断言Assert.isTrue(...)
     */
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Object IllegalArgumentExceptionHandler(IllegalArgumentException e,HttpServletResponse response) {
        log.error("统一异常处理器捕获【spring Assert断言异常】" ,e);
       return ResultEntity.fail(e.getMessage());
    }

    /**
     *处理其它异常
     */
    @ExceptionHandler(value = Exception.class)
    public Object OtherExceptionHandler(Exception e, HttpServletResponse response, HttpServletRequest request) {
        log.error("统一异常处理器捕获{}【未知异常】{},详情:{}" ,request.getRequestURI(), e.getMessage(), e);
        return  ResultEntity.fail(ErrorEnum.UNKNOWN_ERROR);
    }
}



@Getter
public class CommonException extends RuntimeException {
  private String errorCode;
  private String errorMsg;
  
  public CommonException(String errorMsg,Throwable e) {
    super(e);
    this.errorCode = CommonConstant.FAILED;
    this.errorMsg = errorMsg;
  }
  
  public CommonException(ErrorEnum errorEnum,Throwable e) {
    super(e);
    this.errorCode = errorEnum.getCode();
    this.errorMsg = errorEnum.getMsg();
  }
  
}

2.

public abstract class BaseController {
}

//非必需
public class BaseEntity<T extends Model> extends Model {

}
public interface CEMapper<T> extends BaseMapper<T> {
}
public interface BaseService<T> extends IService<T> {

}
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {


}

 

mybatis-plus:
  type-aliases-package: com.ce.entity   # 注意:对应实体类的路径
  mapper-locations: classpath:/mapper/*Mapper.xml
  global-config:
    db-config:
      id-type: uuid

 

package com.example.demo.util;

import com.baomidou.mybatisplus.annotation.DbType;
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.VelocityTemplateEngine;

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

/**
 *  @author: jwolf
 *  @Date: 2020/7/17
 *  @Description: MP自动生成
 */
public class MybatisPlusGenerator {

    public static void main(String[] args) {

        AutoGenerator autoGenerator = new AutoGenerator();
        autoGenerator.setTemplateEngine(new VelocityTemplateEngine());
        //全局配置
        GlobalConfig gc = new GlobalConfig();
        String userDir = System.getProperty("user.dir");
        gc.setOutputDir(userDir + "/src/main/java");
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(false);
        gc.setAuthor(scanner("请输入author"));
        gc.setSwagger2(false);

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setEntityName("%s");
        autoGenerator.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.H2);
        dsc.setDriverName("org.h2.Driver");
        dsc.setUsername("sa");
        dsc.setPassword("admin");
        dsc.setUrl("jdbc:h2:file:D:/test");
        autoGenerator.setDataSource(dsc);

        // 自定义输出配置,主要是xml输出到resources目录下
        InjectionConfig cfg =
                new InjectionConfig() {
                    @Override
                    public void initMap() {
                        // to do nothing
                    }
                };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(
                new FileOutConfig("/templates/mapper.xml.vm") {
                    @Override
                    public String outputFile(TableInfo tableInfo) {
                        return userDir
                                + "/src/main/resources/mapper/"
                                + tableInfo.getEntityName()
                                + "Mapper"
                                + StringPool.DOT_XML;
                    }
                });

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

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass("com.construn.vehicle.common.base.controller.BaseController");
        strategy.setInclude(scanner("请输入表名,多个表用英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("t_");
        autoGenerator.setStrategy(strategy);

        // 置父包,其它都是相对父包路径
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.example.demo");
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setEntity("entity");
        pc.setXml("mapper");
        autoGenerator.setPackageInfo(pc);
        // 执行生成
        autoGenerator.execute();
    }

    /** 读取控制台内容 */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder builder = new StringBuilder();
        builder.append("请输入" + tip + ":");
        System.out.println(builder.toString());
        if (scanner.hasNext()) {
            String in = scanner.next();
            if (StringUtils.isNotEmpty(in)) {
                return in;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
}

 

 

   <!--MP代码自动生成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <property name="LOG_HOME" value="/home/xxLog"/>
    <property name="CONSOLE_LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss}][%thread][%-5level][%logger:%line]%n %msg%n"/>

    <!--控制台-->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="ALL_LEVEL_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_HOME}/all_level/all_level.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <FileNamePattern>${LOG_HOME}/all_level/all_level.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            <MaxHistory>10</MaxHistory>
            <MaxFileSize>2048MB</MaxFileSize>
            <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    
    <!-- 打印sql -->
    <logger name="com.xx.mapper" level="DEBUG"/>
    <!--eureka上报心跳日志不打印-->
    <logger name="com.netflix.discovery.shared.resolver.aws.ConfigClusterResolver" level="WARN"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="ALL_LEVEL_FILE"/>
    </root>
</configuration>

 

    原文作者:jwolf2
    原文地址: https://blog.csdn.net/qq_39506978/article/details/114810377
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。