栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis Plus自动生成代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis Plus自动生成代码

mybatis-plus自动生成代码
  • 一、简易生成代码
  • 二、指定生成的样式,并且不在一个模块
    • 1.父pom文件配置
    • 2.子模块pom文件配置
    • 3.准备vm文件
    • 4.设置MyBatisPlusGenerator.java
    • 5.运行MyBatisPlusGenerator.java文件
    • 6.运行sign-auth模块,解决异常

一、简易生成代码
public class MpCode {
    public static void main(String[] args) {
        generate();
    }
    private  static  void generate(){
        FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/life-sign?serverTimezone=UTC", "root", "root")
                .globalConfig(builder -> {
                    builder.author("lh") // 设置作者
                            // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .outputDir("E:\IDEA_MY\life-sign\sign-common\sign-code\src\main\java"); // 指定输出目录  和自己项目src一一对应
                })
                .packageConfig(builder -> {
                    builder.parent("com.luck.sign") // 设置父包名
                            .moduleName(null) // 设置父包模块名  解决路径冲突
                            .serviceImpl("service.impl") //自定义包名imp 官方的是impi
                            .entity("entity") //设置实体包为pojo
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\IDEA_MY\life-sign\sign-common\sign-code\src\main\resources\mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.entityBuilder().enableLombok();//使用lombok
                    builder.controllerBuilder().enableHyphenStyle()
                            .enableRestStyle();//开启RestController
                    builder.addInclude("sign_tag"); // 设置需要生成的表名

                })
//                  .templateEngine(new VelocityTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

二、指定生成的样式,并且不在一个模块

1.父pom文件配置

我是在父pom文件里进行的依赖管理



    4.0.0

    com.luck
    life-sign
    1.0-SNAPSHOT
    
        sign-auth
        sign-common
        sign-work
    

    
    pom

    
        UTF-8
        1.8
        1.8
    

    
        
            
            
            
                io.springfox
                springfox-swagger-ui
                2.9.2
            

            
            
                io.springfox
                springfox-swagger2
                2.9.2
            

            
            
                org.springframework.cloud
                spring-cloud-dependencies
                Hoxton.SR1
                pom
                import
            

            
            
                org.springframework.boot
                spring-boot-dependencies
                2.2.2.RELEASE
                pom
                import
            

            
                mysql
                mysql-connector-java
                8.0.27
            
            
                org.mybatis.spring.boot
                mybatis-spring-boot-starter
                2.1.4
            
            
                com.baomidou
                mybatis-plus-boot-starter
                3.4.1
            
            
                com.alibaba
                druid
                1.1.23
            
            
                junit
                junit
                4.13
                test
            
            
            
            
                org.projectlombok
                lombok
                1.18.22
            
        
    



2.子模块pom文件配置

父模块管理了依赖,对于父模块里面有的,子模块导入,就不需要写版本号了



    
        sign-common
        com.luck
        1.0-SNAPSHOT
    
    4.0.0
    jar
    sign-code
    
        
            io.springfox
            springfox-swagger-ui
        
        
            io.springfox
            springfox-swagger2
        

        
        
            org.apache.velocity
            velocity
            1.7
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        
        
            com.baomidou
            mybatis-plus-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            mysql
            mysql-connector-java
        
        
            org.projectlombok
            lombok
        
    


以上模块的导入,针对mybatis-plus自动生成代码的功能,主要如下几个依赖

        
        
            org.apache.velocity
            velocity
            1.7
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        
        
            com.baomidou
            mybatis-plus-boot-starter
        
3.准备vm文件

资源链接如下,若下载不了,可留言
mybatis-plus自动生成代码的自定义引擎文件(vm文件)

4.设置MyBatisPlusGenerator.java

用心看,铁子们应该看的懂

package com.luck.sign.util;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;

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


public class MyBatisPlusGenerator {
    private static String module;
    private static String PACKAGE = "com.luck.sign";
    private static String AUTHOR = "lh";
    private static String DATA_USER_NAME = "root";
    private static String DATA_PASSWORD = "root";
    private static String DATA_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    private static String DATA_URL = "jdbc:mysql://127.0.0.1:3306/life-sign?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
    private static String PATH_MAPPER  = "/src/main/java/com/luck/sign/";
    private static String PATH_MAPPER_XML = "/src/main/resources/mapper/";
    private static String PATH_CONTROLLER = "/src/main/java/com/luck/sign/";
    private static String PATH_SERVICE = "/src/main/java/com/luck/sign/";
    private static String PATH_SERVICE_IMP = "/src/main/java/com/luck/sign/";
    private static String PATH_ENTITY = "/sign-common/sign-code/src/main/java/com/luck/sign/";


    public static void main(String[] args) {
        module = "/" + scanner("要输入到哪个项目?");
        String[] tables = scanner("请输入要生成的表名多个用 , 分割").split(",");
        for (String table : tables) {
            shell(table);
        }
    }
    public static String scanner(String someThing) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + someThing + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String sc = scanner.next();
            if ("" != sc && null != sc) {
                return sc;
            }
        }
        throw new MybatisPlusException("请输入正确的" + someThing + "!");
    }

    private static void shell(String table) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDriverName(DATA_DRIVER_NAME);
        dsc.setUsername(DATA_USER_NAME);
        dsc.setPassword(DATA_PASSWORD);
        dsc.setUrl(DATA_URL);
        mpg.setDataSource(dsc);

        // 全局配置
        final String projectPath = System.getProperty("user.dir"); // 默认定位到的当前用户目录("user.dir")(即工程根目录) https://blog.csdn.net/qq_29964641/article/details/86686585
        GlobalConfig gc = new GlobalConfig();
        gc.setAuthor(AUTHOR);//作者名称
        gc.setDateType(DateType.ONLY_DATE);
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setServiceName("%sService"); //自定义文件命名,注意 %s 会自动填充表实体属性! %s作为占位符
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setSwagger2(true);// 是否开启Swagger2模式
        gc.setFileOverride(true); //重新生成时文件是否覆盖
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
//        gc.setIdType(IdType.ID_WORKER_STR); //主键策略
//        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setControllerName("%sController");
        mpg.setGlobalConfig(gc);


        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE);
        pc.setMapper("mapper");//dao
        pc.setService("service");//servcie
        pc.setController("controller");//controller
        pc.setEntity("entity");
//        pc.setModuleName("model名"); 自定义包名

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
//                //表信息
                String name = this.getConfig().getStrategyConfig().getColumnNaming().name();
            }
        };

        // 模板引擎是 freemarker
        // 自定义controller的代码模板
        // 如果模板引擎是 velocity
        String templatePath = "/template/Mapper.xml.vm";
        // 自定义输出配置
        List focList = new ArrayList<>();

        // 自定义配置会被优先输出,配置mapper.xml
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //根据自己的位置修改
                return projectPath  + module + PATH_MAPPER_XML + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        //控制层
        templatePath = "/template/Controller.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_CONTROLLER + "controller";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getControllerName());
                return entityFile;
            }
        });

        //业务层
        templatePath = "/template/Service.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_SERVICE + "service";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceName());
                return entityFile;
            }
        });
        templatePath = "/template/ServiceImpl.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath  + module + PATH_SERVICE_IMP + "service/impl";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getServiceImplName());
                return entityFile;
            }
        });

        //数据层
        templatePath = "/template/Mapper.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + module +PATH_MAPPER + "mapper";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getMapperName());
                return entityFile;
            }
        });

        //数据层
        templatePath = "/template/Entity.java.vm";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 + pc.getModuleName()
                String expand = projectPath + PATH_ENTITY + "entity";
                String entityFile = String.format((expand + File.separator + "%s" + ".java"), tableInfo.getEntityName());
                return entityFile;
            }
        });
        mpg.setPackageInfo(pc);
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);


        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        templateConfig.setService("/template/Service.java.vm");
        templateConfig.setServiceImpl("/template/ServiceImpl.java.vm");
        templateConfig.setEntity("/template/Entity.java.vm");
        templateConfig.setMapper("/template/Mapper.java.vm");
        templateConfig.setController("/template/Controller.java.vm");
        //        //此处设置为null,就不会再java下创建xml的文件夹了
        templateConfig.setXml("/template/Mapper.xml.vm");
        mpg.setTemplate(templateConfig);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel); // 数据库表映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel); //数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(table); //table 表名对那一张表生成代码
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
//        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); // 公共父类
//        strategy.setSuperEntityColumns("id"); //         写于父类中的公共字段
//        strategy.setTablePrefix("t_");  //生成实体时去掉表前缀
//        strategy.setRestControllerStyle(true); //restful api风格控制器
//        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());//默认模板引擎
        mpg.execute();

    }

    
    private String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    
    public String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }
}

5.运行MyBatisPlusGenerator.java文件


6.运行sign-auth模块,解决异常
问题:
因为在MyBatisPlusGenerator.java 的全局参数配置重开启了swagger,但是模块并没有引入相关依赖
解决:
1.因为其他模块都会引入sign-code模块,所以在sign-code模块里引入
2.配置swagger.config,否则swagger不能正常访问

        
            io.springfox
            springfox-swagger-ui
        
        
            io.springfox
            springfox-swagger2
        
报错:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'signOpenidController' defined in file [E:IDEA_MYlife-signsign-authtargetclassescomlucksigncontrollerSignOpenidController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'signOpenidServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luck.sign.mapper.SignOpenidMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
	... ...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'signOpenidServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luck.sign.mapper.SignOpenidMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
	... ...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.luck.sign.mapper.SignOpenidMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE]
	... ...
解决方式:
在启动类加注释 @MapperScan("com.luck.sign.mapper"),再运行即可

@MapperScan("com.luck.sign.mapper")
@SpringBootApplication
public class AuthApplication {
    public static void main(String[] args){
        SpringApplication.run(AuthApplication.class,args);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032001.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号