spring boot 代码自动生成器

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

1 准备工具

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

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

3 模版文件

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了~~~喜欢的 点个赞吧~~谢谢

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • jHipster - 微服务搭建 CC_简书[https://www.jianshu.com/u/be0d56c4...
    quanjj阅读 792评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,566评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,713评论 6 342
  • 原则——读书笔记 当面对两种你都需要但看起来矛盾的选择时,你需要耐心思考如何尽最大可能兼顾二者。几乎总有一条道路是...
    文刀创客阅读 291评论 0 1
  • 你是那天边的一朵云,偶尔投影在我的波心,每当我空闲下来就开始与你对话,告诉你那一刻的心情,不论快乐或忧伤,你都会含...
    那年夏天的欧阳阅读 300评论 0 2