SpringBoot+MyBatisPlus 逆向工程 自动生成controller service dao mapper entity

SpringBoot+MyBatisPlus 逆向工程 自动生成controller service dao mapper entity

    • maven依赖
    • banner文件(可有可无)
    • 代码生成器
    • 测试
    • 说明

maven依赖

<dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 代码生成配置 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>
        <!-- Velocity(默认) -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <!-- 数据库 oracle-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4.0-atlassian-hosted</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>


    </dependencies>

banner文件(可有可无)

banner文件内容来源互联网 纯属是个人爱好

===================== Welcome ========================
         _______  _______  _______  _______
        (  ____ \(  ____ \(  ____ \(  ____ )
        | (    \/| (    \/| (    \/| (    )|
        | (_____ | (__    | (__    | (____)|
    God is in his heaven, all's right with the world.
        (_____  )|  __)   |  __)   |     __)
              ) || (      | (      | (\ (
        /\____) || (____/\| (____/\| ) \ \__
        \_______)(_______/(_______/|/   \__/

===================== Hello World =====================

                       _ooOoo_
                      o8888888o
                      88" . "88
                      (| -_- |)
                       O\ = /O
                   ____/`---'\____
                 .   ' \\| |// `.
                  / \\||| : |||// \
                / _||||| -:- |||||- \
                  | | \\\ - /// | |
                | \_| ''\---/'' | |
                 \ .-\__ `-` ___/-. /
              ___`. .' /--.--\ `. . __
           ."" '< `.___\_<|>_/___.' >'"".
          | | : `- \`.;`\ _ /`;.`/ - ` : | |
            \ \ `-. \_ __\ /__ _/ .-` / /
    ======`-.____`-.___\_____/___.-`____.-'======
                       `=---='

    .............................................
             佛祖镇楼                  BUG辟易
     佛曰:
             写字楼里写字间,写字间里程序员;
             程序人员写程序,又拿程序换酒钱。
             酒醒只在网上坐,酒醉还来网下眠;
             酒醉酒醒日复日,网上网下年复年。
             但愿老死电脑间,不愿鞠躬老板前;
             奔驰宝马贵者趣,公交自行程序员。
             别人笑我忒疯癫,我笑自己命太贱;
             不见满街漂亮妹,哪个归得程序员?

===================== Have a good time ================

代码生成器

public class MybatisGenerator {

    public static void getAutoGenerator(String outputDir,String[] include,String driverName,String url,String username,String password,String moduleName,String packageName){
        File outputFile = new File(outputDir);
        //配置xml配置项
        List<String> warnings = new ArrayList<>();
        try {
            if(!outputFile.exists()){
                FileUtils.forceMkdir(outputFile);
            }
            Configuration configuration = new Configuration();
            Context context = new Context(ModelType.CONDITIONAL);
            context.setTargetRuntime("MyBatis3");
            context.setId("defaultContext");
            //生成的Java文件的编码
            context.addProperty("javaFileEncoding","utf-8");
            context.addProperty("beginningDelimiter","`");
            context.addProperty("endingDelimiter","`");
            //格式化java代码
            context.addProperty("javaFormatter","org.mybatis.generator.api.dom.DefaultJavaFormatter");
            //格式化xml代码
            context.addProperty("xmlFormatter","org.mybatis.generator.api.dom.DefaultXmlFormatter");
            //格式化信息
            PluginConfiguration pluginConfiguration = new PluginConfiguration();
            pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
            pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.ToStringPlugin");
            pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin");
            context.addPluginConfiguration(pluginConfiguration);

            //设置是否去除生成注释
            CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
            commentGeneratorConfiguration.addProperty("suppressAllComments","true");
            commentGeneratorConfiguration.addProperty("suppressDate","true");
            context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);

            //数据库
            getJdbcConnectionConfiguration(context,driverName,url,username,password);
            //数据库 - 表
            getTableConfiguration(context,include,driverName,url,username,password);
            //数据库 - 实体类
            getJavaModelGeneratorConfiguration(context,outputDir,moduleName,packageName);
            // dao
            getJavaClientGeneratorConfiguration(context,outputDir,moduleName,packageName);
            // mapper
            getSqlMapGeneratorConfiguration(context,outputDir,moduleName);
            //添加context
            configuration.addContext(context);
            DefaultShellCallback callback = new DefaultShellCallback(true);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration,callback, warnings);
            myBatisGenerator.generate(null);
            System.out.println("生成Mybatis配置成功!");
            System.out.println("outputDir:"+outputDir);
        } catch (InvalidConfigurationException | SQLException | IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(outputFile.exists()){
                try {
                    Runtime.getRuntime().exec("cmd /c start " + outputFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 数据库 - 连接
     */
    private static void getJdbcConnectionConfiguration(Context context,String driverName,String url,String username,String password){
        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
        jdbcConnectionConfiguration.setDriverClass(driverName);
        jdbcConnectionConfiguration.setConnectionURL(url);
        jdbcConnectionConfiguration.setUserId(username);
        jdbcConnectionConfiguration.setPassword(password);
        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
    }

    /**
     * 数据库 - 表
     */
    private static void getTableConfiguration(Context context,String[] tableNames,String driverName,String url,String username,String password){
        if(tableNames.length == 0){
            List<String> list= getTableName(driverName,url,username,password);
            tableNames = list.toArray(new String[0]);
        }
        for (String tableName:tableNames){
            TableConfiguration tableConfiguration = new TableConfiguration(context);
            tableConfiguration.setTableName(tableName);

            tableConfiguration.setCountByExampleStatementEnabled(false);
            tableConfiguration.setDeleteByExampleStatementEnabled(false);
            tableConfiguration.setUpdateByExampleStatementEnabled(false);
            tableConfiguration.setSelectByExampleStatementEnabled(false);

            tableConfiguration.setInsertStatementEnabled(true);
            tableConfiguration.setDeleteByPrimaryKeyStatementEnabled(true);
            tableConfiguration.setUpdateByPrimaryKeyStatementEnabled(true);
            tableConfiguration.setSelectByPrimaryKeyStatementEnabled(true);

            tableConfiguration.addProperty("modelOnly","false");
            tableConfiguration.addProperty("useActualColumnNames","false");
            context.addTableConfiguration(tableConfiguration);
        }
    }

    /**
     *  实体类
     */
    private static void getJavaModelGeneratorConfiguration(Context context,String outputDir,String moduleName,String packageName){
        JavaModelGeneratorConfiguration modelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
      /*  modelGeneratorConfiguration.setTargetProject("src/main/java");*/
        modelGeneratorConfiguration.setTargetProject(outputDir);
        modelGeneratorConfiguration.setTargetPackage(packageName+"."+moduleName+".entity");
        modelGeneratorConfiguration.addProperty("enableSubPackages","true");
        modelGeneratorConfiguration.addProperty("trimStrings","true");
        context.setJavaModelGeneratorConfiguration(modelGeneratorConfiguration);
    }

    /**
     *  dao
     */
    private static void getJavaClientGeneratorConfiguration(Context context,String outputDir,String moduleName,String packageName){
        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
        /*javaClientGeneratorConfiguration.setTargetProject("src/main/java");*/
        javaClientGeneratorConfiguration.setTargetProject(outputDir);
        javaClientGeneratorConfiguration.setTargetPackage(packageName+"."+moduleName+".dao");
        javaClientGeneratorConfiguration.addProperty("enableSubPackages","true");
        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    }

    /**
     *  mapper
     */
    private static void getSqlMapGeneratorConfiguration(Context context,String outputDir,String moduleName){
        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
       /* sqlMapGeneratorConfiguration.setTargetProject("src/main/resources");*/
        sqlMapGeneratorConfiguration.setTargetProject(outputDir);
        sqlMapGeneratorConfiguration.setTargetPackage("mybatis.mapper");
        sqlMapGeneratorConfiguration.addProperty("enableSubPackages","true");
        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
    }


    /**
     * 获取所有表名
     * @return 返回
     */
    private static  List<String> getTableName(String driverName,String url,String username,String password){
        List<String> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName(driverName).newInstance();
            connection = java.sql.DriverManager.getConnection(url, username, password);
            String sql=" SELECT TABLE_NAME FROM information_schema. TABLES WHERE TABLE_SCHEMA = (SELECT DATABASE())";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                list.add(tableName);
            }
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

}

public class MybatisPlusGenerator {

    private static final String AUTHOR = "tomy";

    public static void getAutoGenerator(DbType dbType,String outputDir,String[] include,String driverName,String url,String username,String password,String moduleName,String packageName){
        AutoGenerator generator = new AutoGenerator();
        generator
                .setGlobalConfig(getGlobalConfig(outputDir))
                .setDataSource(getDataSourceConfig(dbType,driverName,url,username,password))
                .setStrategy(getStrategyConfig(include))
                .setPackageInfo(getPackageConfig(moduleName, packageName))
                .setCfg(getInjectionConfig())
                //设置模板引擎
                .setTemplateEngine(new VelocityTemplateEngine())
                .setTemplate(getTemplateConfig())
        ;
        generator.execute();
    }

    /**
     * 全局配置
     */
    private static GlobalConfig getGlobalConfig(String outputDir) {
        GlobalConfig config = new GlobalConfig();
        return config
                // 是否支持AR模式
                .setActiveRecord(true)
                // 作者
                .setAuthor(AUTHOR)
                // 生成路径,是否覆盖
                .setOutputDir(outputDir).setFileOverride(true)
                // 主键策略,数据库自增
                .setIdType(IdType.AUTO)
                // 设置生成的service接口的名字的首字母是否为I(默认Service类前面有一个I)
                // 自定义文件命名,注意 %s 会自动填充表实体属性
                .setXmlName("%sMapper").setMapperName("%sMapper")
                .setServiceName("%sService").setServiceImplName("%sServiceImpl").setControllerName("%sController")
                // 二级缓存mybatis-ehcache,基本ResultMap,基本的列
                .setEnableCache(false).setBaseResultMap(true).setBaseColumnList(true)
                ;
    }


    /**
     * 数据源配置
     */
    private static DataSourceConfig getDataSourceConfig(DbType dbType,String driverName,String url,String username,String password) {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(dbType);
        dsc.setDriverName(driverName);
        dsc.setUrl(url);
        dsc.setUsername(username);
        dsc.setPassword(password);
        dsc.setTypeConvert(new MySqlTypeConvert() {
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                System.out.println("转换类型:" + fieldType);
                //tinyint转换成byte
                if (fieldType.toLowerCase().contains("tinyint")) {
                    return DbColumnType.BYTE;
                }
                //将数据库中datetime转换成date
                if (fieldType.toLowerCase().contains("datetime")) {
                    return DbColumnType.DATE;
                }
                //将数据库中datetime转换成date
                if (fieldType.toLowerCase().contains("date")) {
                    return DbColumnType.DATE;
                }
                //将数据库中blob转换成byte[]
                if (fieldType.toLowerCase().contains("blob")) {
                    return DbColumnType.BYTE_ARRAY;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fieldType);
            }
        });
        return dsc
                ;
    }

    /**
     * 策略配置
     * include:方法内容传值参数,可不传值,
     * 如不传值:则对应数据库全部表,
     * 如传值:则对应填写表
     */
    private static StrategyConfig getStrategyConfig(String[] include) {
        StrategyConfig stConfig = new StrategyConfig();
        return stConfig
                // 全局大写命名
                .setCapitalMode(true)
                // 数据库表映射到实体的命名策略
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setSuperEntityClass(Model.class)
                .setEntityLombokModel(true)
                .setEntitySerialVersionUID(true)
                .setEntityTableFieldAnnotationEnable(true)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                // 需要生成的表  只能配置一项!
                .setInclude(include)
                // 排除生成的表
                // .setExclude("")
                .setEntityBuilderModel(true)
                ;
    }

    /**
     * 包配置
     */
    private static PackageConfig getPackageConfig(String moduleName, String packageName) {
        PackageConfig pkConfig = new PackageConfig();
        return pkConfig
                .setModuleName(moduleName)
                // 设置父包
                .setParent(packageName)
                // 实体类
                .setEntity("entity")
                // 接口映射的xml文件
                .setXml("mapper")
                // dao层
                .setMapper("dao")
                // Service 层
                .setService("service")
                // Controller 层
                .setController("controller")
                ;
    }

    /**
     * 自定义配置
     */
    private static InjectionConfig getInjectionConfig() {
        return new InjectionConfig() {
            @Override
            public void initMap() {

            }
        };
    }

    /**
     * 自定义代码模板
     * 指定自定义模板路径, 位置:/resources/templates/entity.java.ftl(或者是.vm)
     * 注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别
     * 当前一下的模板信息是从jar包源码的/resources/templates找到填写,
     * 如没有自定义有模板,可直接返回null即可
     */
    private static TemplateConfig getTemplateConfig() {
        return new TemplateConfig()
                .setEntity("templates/entity.java")
                .setEntityKt("templates/entity.kt")
                .setXml("templates/mapper.xml")
                .setMapper("templates/mapper.java")
                .setService("templates/service.java")
                .setServiceImpl("templates/serviceImpl.java")
                ;
    }
}

测试

/**
     * MybatisPlus(mysql数据库)
     */
    @Test
    void createMySqlToMybatisPlus() {
        String outputDir = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+ File.separator+"myCode"+ File.separator+ UUID.randomUUID().toString();
        //不填写则全部表,生成在桌面(自动弹出文件目录)
        String[] include = new String[]{"sys_user_post","sys_user_role"};
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/tomy";
        String username = "root";
        String password = "root";
        String packageName = "com.tomy";
        String moduleName = "springbootbackstage";
        MybatisPlusGenerator.getAutoGenerator(DbType.MYSQL, outputDir,include,driverName,url,username,password,moduleName,packageName);
    }

    /**
     * MybatisPlus(Oracle数据库)
     */
    @Test
    void createOracleToMybatisPlus() {
        String outputDir = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+ File.separator+"myCode"+ File.separator+ UUID.randomUUID().toString();
        //不填写则全部表,生成在桌面(自动弹出文件目录)
        String[] include = new String[]{"SMS_ORDER","SMS_ORDER_LIST","SMS_ORDER_TRADE"};
        String driverName = "oracle.jdbc.OracleDriver";
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        String username = "c##tomy";
        String password = "123456";
        String packageName = "com.tomy";
        String moduleName = "sms";
        MybatisPlusGenerator.getAutoGenerator(DbType.ORACLE, outputDir,include,driverName,url,username,password,moduleName,packageName);
    }


    /**
     * Mybatis(MySql数据库)
     */
    @Test
    void createMySqlToMybatis() {
        String outputDir = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+ File.separator+"myCode"+ File.separator+ UUID.randomUUID().toString();
        //不填写则全部表,生成在桌面(自动弹出文件目录)
        String[] include = new String[]{"t_users"};
        String driverName = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1:3306/testdb";
        String username = "root";
        String password = "root";
        String packageName = "com.tomy";
        String moduleName = "tomy";
        MybatisGenerator.getAutoGenerator(outputDir,include,driverName,url,username,password,moduleName,packageName);
    }

说明

逆向工程为SpringBoot项目,代码生成后会在桌面上创建文件夹,默认在程序执行完后自动打开文件夹,未完。。。。

个人学习记录,仅供参考!

你可能感兴趣的:(工具类,java,mybatis,mysql,spring,boot)