SpringBoot极简教程 · Spring Boot Spring-Boot持久层

spring boot 代码自动生成器

2018-10-25  本文已影响1022人  戒烟人

本例,可根据数据库表名,表结构自动生成controller,service,model,dao,mapper.xml ,减少了程序员们的重复劳动,你是不是最烦每次写新模块的时候,新建一个controller ,service然后把 简单的增删改查 业务重复的写一边?只是表名不一样而已,其他的逻辑几乎一模一样,重复到想吐,这位同学(敲黑板!!!),你找到组织了,当你看到这片文章的时候你的问题就解决了,废话不多说,开始:

1 准备工具

1 IDEA (随便哪个版本都可以)

2 mybatis-generator(含一对多,一对一插件,密码:pntd)

3 模版文件(密码:74l7)

4 jdk 1.8 环境

5 mysql数据库

2 开始

1 创建一个spring boot 工程 添加勾选 web,mysql,mybatis 依赖

image image image image image

点击next

image image

注: 可能有的同学会卡到这个界面 一直在resolving ,这时候 点击左上角file->close project,在进来,刷新下maven 依赖 就可以了,如下图:

image image image image

2 添加maven 的pom依赖


<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.ytx</groupId>

<artifactId>store</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>jar</packaging>

<properties>

<java.version>1.8</java.version>

</properties>

    <parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.10.RELEASE</version>

</parent>

<dependencies>

        <dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</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-configuration-processor</artifactId>

<optional>true</optional>

</dependency>

        <dependency>

<groupId>commons-codec</groupId>

<artifactId>commons-codec</artifactId>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.6</version>

</dependency>

<dependency>

<groupId>com.google.guava</groupId>

<artifactId>guava</artifactId>

<version>23.0</version>

</dependency>

        <dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency>

        <dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>1.3.2</version>

</dependency>

        <dependency>

<groupId>tk.mybatis</groupId>

<artifactId>mapper-spring-boot-starter</artifactId>

<version>1.1.4</version>

</dependency>

        <dependency>

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper-spring-boot-starter</artifactId>

<version>1.2.2</version>

</dependency>

        <dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.44</version>

</dependency>

        <dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.6</version>

</dependency>

        <dependency>

<groupId>org.freemarker</groupId>

<artifactId>freemarker</artifactId>

<version>2.3.23</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.mybatis.generator</groupId>

<artifactId>mybatis-generator-core</artifactId>

<version>1.3.5</version>

<scope>test</scope>

</dependency>

        <dependency>

<groupId>dom4j</groupId>

<artifactId>dom4j</artifactId>

<version>1.6.1</version>

</dependency>

        <dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

        <dependency>

<groupId>cn.hutool</groupId>

<artifactId>hutool-all</artifactId>

<version>4.1.1</version>

</dependency>

        <dependency>

<groupId>cn.jpush.api</groupId>

<artifactId>jpush-client</artifactId>

<version>3.3.7</version>

</dependency>

        <dependency>

<groupId>io.jsonwebtoken</groupId>

<artifactId>jjwt</artifactId>

<version>0.6.0</version>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

<plugin>

<artifactId>maven-compiler-plugin</artifactId>

<configuration>

<source>${java.version}</source>

<target>${java.version}</target>

<encoding>UTF-8</encoding>

</configuration>

</plugin>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-archetype-plugin</artifactId>

<version>2.2</version>

</plugin>

</plugins>

</build>

<repositories>

<repository>

<id>aliyun-repos</id>

<url>http://maven.aliyun.com/nexus/content/groups/public/</url>

<snapshots>

<enabled>false</enabled>

</snapshots>

</repository>

</repositories>

<pluginRepositories>

<pluginRepository>

<id>aliyun-plugin</id>

<url>http://maven.aliyun.com/nexus/content/groups/public/</url>

<snapshots>

<enabled>false</enabled>

</snapshots>

</pluginRepository>

</pluginRepositories>

</project>

2 在src/main/java/com.generator下创建 core 目录 并拷贝一下代码到目录中:

/**
 * 项目常量
 */
public final class ProjectConstant {
    public static final String BASE_PACKAGE = "com.generator";//项目基础包名称,根据自己公司的项目修改

    public static final String MODEL_PACKAGE = BASE_PACKAGE + ".model";//Model所在包
    public static final String MAPPER_PACKAGE = BASE_PACKAGE + ".dao";//Mapper所在包
    public static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";//Service所在包
    public static final String SERVICE_IMPL_PACKAGE = SERVICE_PACKAGE + ".impl";//ServiceImpl所在包
    public static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".web";//Controller所在包
    public static final String INPUT_PACKAGE=BASE_PACKAGE+".input";//input 所在包

    public static final String MAPPER_INTERFACE_REFERENCE = BASE_PACKAGE + ".core.Mapper";//Mapper插件基础接口的完全限定名

}

此类定义生成的 包的名字
3 在src/test/java 下创建 CodeGenerator类

/**
 * 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
 */
public class CodeGenerator {
    //JDBC配置,请修改为你项目的实际配置
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/ytx";
    private static final String JDBC_USERNAME = "root";
    private static final String JDBC_PASSWORD = "root";
    private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";

    private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
    private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/generator/template";//模板位置

    private static final String JAVA_PATH = "/src/main/java"; //java文件路径
    private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径

    private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径
    private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
    private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径
    private static final String PACKAGE_PATH_INPUT = packageConvertPath(INPUT_PACKAGE);//生成的Input存放路径


    private static final String AUTHOR = "zjz";//@author
    private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date

    public static void main(String[] args) {
        genCode("admin_user");//管理员用户表
        //genCode("user");
        genCode("role");//角色表
        genCode("menu");//菜单表
        genCode("role_menu");//角色—菜单表
        genCode("sys_dict");//字典表
        //genCodeByCustomModelName("输入表名","输入自定义Model名称");
    }

    /**
     * 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。
     * 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
     * @param tableNames 数据表名称...
     */
    public static void genCode(String... tableNames) {
        for (String tableName : tableNames) {
            String modelName=tableNameConvertUpperCamel(tableName);
            genCodeByCustomModelName(tableName, modelName);
        }
    }

    /**
     * 通过数据表名称,和自定义的 Model 名称生成代码
     * 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
     * @param tableName 数据表名称
     * @param modelName 自定义的 Model 名称
     */
    public static void genCodeByCustomModelName(String tableName, String modelName) {
        //genModelAndMapper(tableName, modelName);
        genService(tableName, modelName);
        genController(tableName, modelName);
        genInput(tableName,modelName);

//        genModelAndMapper();
    }



    /**
     * 自动生成model和mapper
     * @param tableName
     * @param modelName
     */
    public static void genModelAndMapper(String tableName, String modelName) {
        Context context = new Context(ModelType.FLAT);
        context.setId("Potato");
        context.setTargetRuntime("MyBatis3Simple");
        context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
        context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");

        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
        jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
        jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
        jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

        PluginConfiguration pluginConfiguration = new PluginConfiguration();
        pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
        pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE);
        pluginConfiguration.setConfigurationType("");
        context.addPluginConfiguration(pluginConfiguration);

        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
        javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE);
        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
        sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
        sqlMapGeneratorConfiguration.setTargetPackage("mapper");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
        javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE);
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

        TableConfiguration tableConfiguration = new TableConfiguration(context);
        tableConfiguration.setTableName(tableName);
        if (StringUtils.isNotEmpty(modelName)){
            tableConfiguration.setDomainObjectName(modelName);
        }
        tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
        tableConfiguration.setCountByExampleStatementEnabled(true);//通过example 计数
        tableConfiguration.setUpdateByExampleStatementEnabled(true);//通过example 修改
        tableConfiguration.setDeleteByExampleStatementEnabled(true);//通过example 删除
        tableConfiguration.setSelectByExampleStatementEnabled(true);//通过example 查找
        context.addTableConfiguration(tableConfiguration);

        List<String> warnings;
        MyBatisGenerator generator;
        try {
            Configuration config = new Configuration();
            config.addContext(context);
            config.validate();

            boolean overwrite = true;
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            warnings = new ArrayList<String>();
            generator = new MyBatisGenerator(config, callback, warnings);
            generator.generate(null);
        } catch (Exception e) {
            throw new RuntimeException("生成Model和Mapper失败", e);
        }

        if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
            throw new RuntimeException("生成Model和Mapper失败:" + warnings);
        }
        if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
        System.out.println(modelName + ".java 生成成功");
        System.out.println(modelName + "Mapper.java 生成成功");
        System.out.println(modelName + "Mapper.xml 生成成功");
    }

    /**
     * 自动生成service
     * @param tableName
     * @param modelName
     */
    public static void genService(String tableName, String modelName) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", tableNameConvertLowerCamel(tableName));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            cfg.getTemplate("p-service.ftl").process(data,
                    new FileWriter(file));
            System.out.println(modelNameUpperCamel + "Service.java 生成成功");

            File file1 = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }
            cfg.getTemplate("p-service-impl.ftl").process(data,
                    new FileWriter(file1));
            System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成Service失败", e);
        }
    }

    /**
     * 自动生成controller
     * @param tableName
     * @param modelName
     */
    public static void genController(String tableName, String modelName) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //cfg.getTemplate("controller-restful.ftl").process(data, new FileWriter(file));
            cfg.getTemplate("p-controller.ftl").process(data, new FileWriter(file));

            System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成Controller失败", e);
        }

    }

    /**
     * 自动生成input对象
     * @param tableName
     * @param modelName
     */
    public static void genInput(String tableName, String modelName) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<>();
            data.put("date", DATE);
            data.put("author", AUTHOR);
            String modelNameUpperCamel = StringUtils.isEmpty(modelName) ? tableNameConvertUpperCamel(tableName) : modelName;
            //data.put("baseRequestMapping", modelNameConvertMappingPath(modelNameUpperCamel));
            data.put("modelNameUpperCamel", modelNameUpperCamel);
            //data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
            data.put("basePackage", BASE_PACKAGE);

            File file = new File(PROJECT_PATH + JAVA_PATH + PACKAGE_PATH_INPUT + modelNameUpperCamel + "Input.java");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //cfg.getTemplate("controller-restful.ftl").process(data, new FileWriter(file));
            cfg.getTemplate("input.ftl").process(data, new FileWriter(file));

            System.out.println(modelNameUpperCamel + "Input.java 生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成Input失败", e);
        }

    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        return cfg;
    }

    private static String tableNameConvertLowerCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, tableName.toLowerCase());
    }

    private static String tableNameConvertUpperCamel(String tableName) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());

    }

    private static String tableNameConvertMappingPath(String tableName) {
        tableName = tableName.toLowerCase();//兼容使用大写的表名
        //return "/" + (tableName.contains("_") ? tableName.replaceAll("_", "/") : tableName);
        return "/"+tableName;
    }

    private static String modelNameConvertMappingPath(String modelName) {
        String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
        return tableNameConvertMappingPath(tableName);
    }

    private static String packageConvertPath(String packageName) {
        return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
    }

}

此类为 代码自动生成器的主函数,配置说明:
JDBC_URL :数据库链接配置
JDBC_USERNAME: 数据库账户名
JDBC_PASSWORD: 数据库密码
只需要配置这三项为你自己数据库的参数即可, 其他暂时不需要管
4 在src/test目录下新建文件目录 resources


image.png

5 配置resources 为资源目录(右键resources)


image.png

6 在resources 目录下新建 模版包 generator.template


image.png
7 将准备工作中的 模版文件下载下来并放置在此目录
image.png

注:这三个模版分别为 生成input(输入参数),controller service接口 和serviceImpl 实现类的三个模版 如果需要可自行扩展
8 将准备工作中的mybatis-generator 文件下载下来解压后放到工程的根目录


image.png

9 打开generator.xml 并编辑


image.png
10 配置要生成的表
假设你的数据 表是这样的:
image.png

admin_user 为管理用户表
menu 为菜单表
role为角色表
role_menu 为角色-菜单 关联表
sys_dict 为字典表
admin_user 与role 为 1对1 的关系
role与role_menu 为1 对多关系
role_menu与menu 为1对1关系
根据你自己的情况生成1对1 和 1 对多的关系映射

image.png
如果不是很清楚怎么配置 可移步到
https://blog.csdn.net/bandaotixiruiqiang/article/details/72478361
进行查看,这里不做太多说明
10 打开idea 的终端
image.png
输入命令
java -jar mybatis.jar -configfile generator.xml -overwrite

敲击回车 然后model,dao,和xml就自动生成了


image.png

(是不是有点小激动?别急高潮还没到,到了我会叫的)

接下来我们来生成controller 和 service
1 在src/main/java/com/generator/core 目录中添加Result类

public class Result<T> {

    private Integer code;

    private String msg;

    private T data;


    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

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

2 在src/main/java/com.generator 下添加util 目录并在目录中添加ResultUtil 工具类

public class ResultUtil {

    public static Result success(Object object){
        Result result = new Result();
        result.setCode(0);
        result.setData(object);
        result.setMsg("成功");
        return result;
    }

    public static Result success(){
        return success(null);
    }

    public static Result error(Integer code,String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

3 添加统一异常处理
在src/main/java/com.generator 下添加 enums 目录并添加 YTXExceptionType 异常类枚举(名字可自行定义)


image.png
public enum YTXExceptionType {//错误类定义
    CAN_NOT_FIND_VALID_CODE(-1,"未找到验证码"),
    MOBILE_INCORRECTNESS(-2,"手机号不正确"),
    VALID_CODE_INCORRECTNESS(-3,"验证码不正确"),
    USER_UNKNOWN(-4,"未知用户"),
    USER_INCORRECT_PASSWORD(-5,"密码不正确"),
    USER_ALREADY_EXIST(-6,"用户已存在"),
    DELETE_FAIL(-7,"删除失败,id不正确"),
    ROLE_ALREADY_EXIST(-8,"角色code已存在"),
    ROLE_HAS_ADMIN_USER(-9,"当前角色下含有用户无法删除"),
    ROLE_NOT_FOUND(-10,"角色不存在"),
    MENU_ALREADY_EXIST(-11,"菜单code已存在"),
    MENU_DELETE_HAS_SUB(-12,"菜单包含子菜单,请先删除子菜单"),
    MENU_NOT_FOUND(-13,"菜单id不存在"),
    ROLE_MENU_ALREADY_EXIST(-14,"当前角色已存在该菜单")
    ;

    private Integer code;
    private String msg;

    YTXExceptionType(Integer code, String msg){
        this.code=code;
        this.msg=msg;
    }
    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

在src/main/java/com.generator 下 添加 exception目录 并添加业务异常类


image.png
public class YTXException extends RuntimeException {
    private Integer code;

    public YTXException(YTXExceptionType exceptionType){
        super(exceptionType.getMsg());
        this.code=exceptionType.getCode();
    }

    public YTXException(Integer code, String msg){
        super(msg);
        this.code = code;
    }

    public YTXException(YTXExceptionType exceptionType, String msg){
        super(msg);
        this.code = exceptionType.getCode();
    }


    public Integer getCode() {
        return code;
    }

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

在src/main/java/com.generator 下添加目录 handle 并 添加YTXExceptionHandler 异常处理类(名字可自定义)


image.png
@ControllerAdvice
public class YTXExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(YTXExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        e.printStackTrace();
        if(e instanceof YTXException){//业务异常
            YTXException ytxException=(YTXException) e;
            return ResultUtil.error(ytxException.getCode(),ytxException.getMessage());
        }else if(e instanceof BindException){//参数传入异常
            BindException exception=(BindException)e;
            return ResultUtil.error(-99,
                    "参数:["+exception.getFieldError().getField()+"]错误," +exception.getFieldError().getDefaultMessage());
        }else if(e instanceof MethodArgumentNotValidException){//参数传入异常

            MethodArgumentNotValidException exception=(MethodArgumentNotValidException)e;

            BindingResult result=exception.getBindingResult();
            return ResultUtil.error(-99,
                    "参数:["+result.getFieldError().getField()+"]错误," +result.getFieldError().getDefaultMessage());
        } else if(e instanceof NoHandlerFoundException) {

            String url=((NoHandlerFoundException) e).getRequestURL();

            return ResultUtil.error(-99,"未知的接口:"+url);

        } else if(e instanceof HttpRequestMethodNotSupportedException) {

            String method=((HttpRequestMethodNotSupportedException) e).getMethod();

            return ResultUtil.error(-99,"请求方式不正确:"+method);

        } else {
            logger.error("[系统异常]",e.getMessage());
            return ResultUtil.error(-1,"[系统异常]");
        }
    }
}

好了 墨迹半天终于到了激动人心的时刻了~~~开始生成我们的控制层代码
打开CodeGenerator


image.png

找到main方法,调用genCode() 传入你的表名 点击左边箭头开始生成


image.png
查看下方日志
image.png
成功!!

当当当当~~oh~~no~~oh~~yes~~终于生成了我们的代码


image.png
让我们看下controller
image.png
增删 改查 一个不少
在看下service
image.png
实现类:
image.png

input 为 定义的常态输入类 内置了 分页参数 和 关键字参数 可根据你自己的需要进行扩展


image.png

终于可以向无聊的重复劳动 说88了~~~喜欢的 点个赞吧~~谢谢

上一篇下一篇

猜你喜欢

热点阅读