Mybatis-Plus代码生成器

运行main方法生成代码

// Copyright 2016-2101 Pica.
package com.pica.cloud.commercialization.crrs.generator;

import com.baomidou.mybatisplus.annotation.DbType;
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 java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MybatisPlusCodeGenerator
 * @Description MybatisPlus代码生成器
 * 使用时注意修改文件路径与本地项目代码存放地址一致
 * @Author Chongwen.jiang
 * @Date 2019/8/14 9:10
 * @ModifyDate 2019/8/14 9:10
 * @Version 1.0
 */
public class MybatisPlusCodeGenerator {

    public static void main(String[] args) {

        //文件输出地址
        String classFileOutputDir = "D:\\Code\\crrs-backend\\src\\main\\java";
        //生成的class文件包名
        String moduleName = "generatorcode";
        //生成xml文件包名
        String xmlOutputDir = "D:\\Code\\crrs-backend\\src\\main\\java\\com\\pica\\cloud\\commercialization\\crrs\\generatxml\\";
        //表名
        String[] tableNames = new String[]{"test_genet", "test_genet2"};


        AutoGenerator generator = new AutoGenerator();

        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        //数据库类型
        dataSourceConfig.setDbType(DbType.POSTGRE_SQL);
        //数据库驱动类
        dataSourceConfig.setDriverName("org.postgresql.Driver");
        //数据库连接地址
        dataSourceConfig.setUrl("jdbc:postgresql://192.168.110.241:5432/crrs?useUnicode=true&useSSL=false&characterEncoding=utf8");
        //数据库用户
        dataSourceConfig.setUsername("crrsuser");
        //数据库密码
        dataSourceConfig.setPassword("123456");
        //数据库schema
        dataSourceConfig.setSchemaName("public");
        generator.setDataSource(dataSourceConfig);


        GlobalConfig globalConfig = new GlobalConfig();
        //生成文件输出地址
        globalConfig.setOutputDir(classFileOutputDir);
        //是否覆盖文件
        globalConfig.setFileOverride(true);
        //XML 二级缓存
        globalConfig.setEnableCache(false);
        //开启 activeRecord 模式
        globalConfig.setActiveRecord(true);
        //作者
        globalConfig.setAuthor("Chongwen.jiang");
        //XML ResultMap(通用查询映射结果)
        globalConfig.setBaseResultMap(true);
        //XML columList(通用查询结果列)
        globalConfig.setBaseColumnList(false);
        //自定义文件命名,注意 %s 会自动填充表实体属性!
        globalConfig.setEntityName("%sEntity");
        globalConfig.setXmlName("%sMapper");
        globalConfig.setServiceName("%sService");
        globalConfig.setServiceImplName("%sServiceImpl");
        globalConfig.setControllerName("%sController");
        //实体类添加swagger注释
        globalConfig.setSwagger2(true);
        generator.setGlobalConfig(globalConfig);


        StrategyConfig strategyConfig = new StrategyConfig();
        //表名生成策略
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        //列生成策略
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        //entity的父类
        strategyConfig.setSuperEntityClass("com.pica.cloud.commercialization.crrs.model.BaseEntity");
        //server接口父类
        strategyConfig.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
        //server实现类的父类
        strategyConfig.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
        // 启用lombok增加实体类的get,set方法简化代码;如果不启用可以改为false
        strategyConfig.setEntityLombokModel(true);
        //restController风格
        strategyConfig.setRestControllerStyle(true);
        //strategyConfig.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        //需要生成代码的表名
        strategyConfig.setInclude(tableNames);
        //使用父类的id
        strategyConfig.setSuperEntityColumns("id");
        strategyConfig.setControllerMappingHyphenStyle(true);
        //实体类是否生成字段常量(默认 false)
        strategyConfig.setEntityColumnConstant(true);
        //Boolean类型字段是否移除is前缀处理
        strategyConfig.setEntityBooleanColumnRemoveIsPrefix(true);
        // strategyConfig.setTablePrefix(pc.getModuleName() + "_");
        generator.setStrategy(strategyConfig);


        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setModuleName(moduleName);
        packageConfig.setParent("com.pica.cloud.commercialization.crrs");
        packageConfig.setController("controller");
        generator.setPackageInfo(packageConfig);


        generator.setTemplate(new TemplateConfig().setXml(null));

        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        injectionConfig.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig(
                "/templates/mapper.xml" + ".vm") {
            // 自定义输出文件目录
            @Override
            public String outputFile(TableInfo tableInfo) {
                return xmlOutputDir + tableInfo.getEntityName() + ".xml";
            }
        }));

        generator.setCfg(injectionConfig);


        generator.execute();


    }

}

结果如下:
在这里插入图片描述

利用maven插件生成代码

在pom.xml文件中加入如下依赖:

<plugin>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatisplus-maven-plugin</artifactId>
    <version>1.0</version>
    <configuration>
        <!-- 输出目录(默认java.io.tmpdir) -->
        <outputDir>e:\cache</outputDir>
        <!-- 是否覆盖同名文件(默认false) -->
        <fileOverride>true</fileOverride>
        <!-- mapper.xml 中添加二级缓存配置(默认true) -->
        <enableCache>true</enableCache>
        <!-- 开发者名称 -->
        <author>Yanghu</author>
        <!-- 是否开启 ActiveRecord 模式(默认true) -->
		<activeRecord>false</activeRecord>
        <!-- 数据源配置,( **必配** ) -->
        <dataSource>
            <driverName>com.mysql.jdbc.Driver</driverName>
            <url>jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&amp;useSSL=false</url>
            <username>root</username>
            <password>123456</password>
        </dataSource>
        <strategy>
			<!-- 字段生成策略,四种类型,从名称就能看出来含义: 
				nochange(默认), 
				underline_to_camel,(下划线转驼峰) 
				remove_prefix,(去除第一个下划线的前部分,后面保持不变) 
				remove_prefix_and_camel(去除第一个下划线的前部分,后面转驼峰) -->
			<naming>remove_prefix_and_camel</naming>
			<!-- 表前缀 -->
			<tablePrefix>bmd_</tablePrefix>
            <!--Entity中的ID生成策略(默认 id_worker)-->
            <idGenType>uuid</idGenType>
            <!--自定义超类-->
            <!--<superServiceClass>com.baomidou.base.BaseService</superServiceClass>-->
            <!-- 要包含的表 与exclude 二选一配置-->
            <!--<include>-->
                <!--<property>sec_user</property>-->
                <!--<property>table1</property>-->
            <!--</include>-->
            <!-- 要排除的表 -->
            <!--<exclude>-->
                <!--<property>schema_version</property>-->
            <!--</exclude>-->
        </strategy>
        <packageInfo>
            <!-- 父级包名称,如果不写,下面的service等就需要写全包名(默认com.baomidou) -->
            <parent>com.baomidou</parent>
            <!--service包名(默认service)-->
            <service>service</service>
            <!--serviceImpl包名(默认service.impl)-->
            <serviceImpl>service.impl</serviceImpl>
            <!--entity包名(默认entity)-->
            <entity>entity</entity>
            <!--mapper包名(默认mapper)-->
            <mapper>mapper</mapper>
            <!--xml包名(默认mapper.xml)-->
            <xml>mapper.xml</xml>
        </packageInfo>
        <template>
        	<!-- 定义controller模板的路径 -->
			<!--<controller>/template/controller1.java.vm</controller>-->
		</template>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
</plugin>


mybatis代码生成器配置

pom.xml文件加入构建插件

 <build>
        <finalName>pica-cloud-health-sms-server</finalName>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                    <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                </configuration>
            </plugin>
        </plugins>
</build>

reources包下xml文件代码:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    <!--<classPathEntry location="D:/dev/maven/repository/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar"/>-->
    <!--<classPathEntry location="F:/joyRepo/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar"/>-->
    <classPathEntry location="C:/Users/DELL/.m2/repository/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar"/>
    <context id="tableEntity" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
            <property name="addRemarkComments" value="true"/>
            <property name="dateFormat" value="false"/>
            <property name="suppressDate" value="false"/>
        </commentGenerator>
        <!--数据库链接URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://192.168.130.200:3306/pica"
                        userId="pica" password="Joa5@73&amp;8yAYJ2fe">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成模型的包名和位置-->
        <javaModelGenerator targetPackage="com.pica.cloud.health.sms.server.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成映射文件的包名和位置-->
        <sqlMapGenerator targetPackage="mybatis" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成DAO的包名和位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.pica.cloud.health.sms.server.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--<table tableName="pica.sms_entity" domainObjectName="SmsEntity"  enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true" enableDeleteByPrimaryKey="true" ></table>-->
        <!--<table tableName="pica.sms_doctor_send" domainObjectName="SmsDoctorSend" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true"></table>-->
        <table tableName="pica.sms_entity_mapping" domainObjectName="SmsEntityMapping" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true"></table>
        <!--<table tableName="pica.sms_doctor_send_detail" domainObjectName="SmsDoctorSendDetail" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true"></table>-->
        <!--<table tableName="pica.sms_doctor_send_record" domainObjectName="SmsDoctorSendRecord" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true"></table>-->
        <!--<table tableName="pica.sms_link_data_stats" domainObjectName="SmsLinkDataStats" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" enableDeleteByPrimaryKey="false" ></table>-->
        <!--<table tableName="pica.sms_reason_mapping" domainObjectName="SmsReasonMapping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="true" enableDeleteByPrimaryKey="true" ></table>-->

    </context>
</generatorConfiguration>


发布了36 篇原创文章 · 获赞 4 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/weixin_41205148/article/details/99561107