springboot + mybatis plus反向生成实体类、接口等文件

经过本人的研究和网上搜索总结了一个完整的配置,代码生成之后,简单的增删改查都不需要写了,复杂的需求还是需要自己编写sql语句的,初学的小伙伴可以参考参考

###首先我们要引入相关的maven依赖包

<dependencies>
		<!-- lombok需要的jar包 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<!-- springboot需要的jar包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- web项目需要的jar包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- MP 核心库 -->
		<dependency> 
	        <groupId>com.baomidou</groupId> 
	        <artifactId>mybatis-plus</artifactId> 
	        <version>2.3</version> 
	    </dependency>
	    <!-- 模板引擎 -->
	    <dependency>
	        <groupId>org.apache.velocity</groupId>
	        <artifactId>velocity</artifactId>
	        <version>1.7</version>
	    </dependency>
	    <!-- oracle驱动 -->
		<dependency>
		    <groupId>com.oracle</groupId>
		    <artifactId>ojdbc6</artifactId>
		    <version>11.2.0.3</version>
		</dependency>
	</dependencies>

###然后我们来实现代码的编写,只需要一个执行类

package com.ycq;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
 * Created by Yangcq on 2018/08/16.
 */
public class Generator {
	
	//项目路径
	private static String canonicalPath = "";

    //基本包名
    private static String basePackage = "com.ycq";
    //作者
    private static String authorName = "Yangcq";
    //要生成的表名
    private static String[] tables = {"JS_ENFOR","JS_DOC"};
    //table前缀
    private static String prefix = "JS_";

    //数据库类型
    private static DbType dbType = DbType.ORACLE;
    //数据库配置四要素
    private static String driverName = "oracle.jdbc.OracleDriver";
    private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    private static String username = "scott";
    private static String password = "scott";


    public static void main(String[] args) {

        AutoGenerator gen = new AutoGenerator();
        
        /**
         * 获取项目路径
         */
		try {
			canonicalPath = new File("").getCanonicalPath();
		} catch (IOException e) {
			e.printStackTrace();
		}

        /**
         * 数据库配置
         */
        gen.setDataSource(new DataSourceConfig()
                .setDbType(dbType)
                .setDriverName(driverName)
                .setUrl(url)
                .setUsername(username)
                .setPassword(password)
                .setTypeConvert(new MySqlTypeConvert() {
                    // 自定义数据库表字段类型转换【可选】
                    //@Override
                    //public DbColumnType processTypeConvert(String fieldType) {
                        //System.out.println("转换类型:" + fieldType);
                        // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                        //    return DbColumnType.BOOLEAN;
                        // }
                        //return super.processTypeConvert(fieldType);
                    //}
                }));

        /**
         * 全局配置
         */
        gen.setGlobalConfig(new GlobalConfig()
                .setOutputDir( canonicalPath + "/src/main/java")//输出目录
                .setFileOverride(true)// 是否覆盖文件
                .setActiveRecord(true)// 开启 activeRecord 模式
                .setEnableCache(false)// XML 二级缓存
                .setBaseResultMap(true)// XML ResultMap
                .setBaseColumnList(true)// XML columList
                .setOpen(false)//生成后打开文件夹
                .setAuthor(authorName)
                // 自定义文件命名,注意 %s 会自动填充表实体属性!
                .setMapperName("%sMapper")
                .setXmlName("%sMapper")
                .setServiceName("%sService")
                .setServiceImplName("%sServiceImpl")
                .setControllerName("%sController")
        );

        /**
         * 策略配置
         */
        gen.setStrategy(new StrategyConfig()
                // .setCapitalMode(true)// 全局大写命名
                //.setDbColumnUnderline(true)//全局下划线命名
                .setTablePrefix(new String[]{prefix})// 此处可以修改为您的表前缀
                .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
                .setInclude(tables) // 需要生成的表
                .setRestControllerStyle(true)
                //.setExclude(new String[]{"test"}) // 排除生成的表
                // 自定义实体父类
                // .setSuperEntityClass("com.baomidou.demo.TestEntity")
                // 自定义实体,公共字段
                //.setSuperEntityColumns(new String[]{"test_id"})
                //.setTableFillList(tableFillList)
                // 自定义 mapper 父类 默认BaseMapper
                //.setSuperMapperClass("com.baomidou.mybatisplus.mapper.BaseMapper")
                // 自定义 service 父类 默认IService
                // .setSuperServiceClass("com.baomidou.demo.TestService")
                // 自定义 service 实现类父类 默认ServiceImpl
                // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
                // 自定义 controller 父类
                //.setSuperControllerClass("com.kichun."+packageName+".controller.AbstractController")
                // 【实体】是否生成字段常量(默认 false)
                // public static final String ID = "test_id";
                // .setEntityColumnConstant(true)
                // 【实体】是否为构建者模型(默认 false)
                // public User setName(String name) {this.name = name; return this;}
                // .setEntityBuilderModel(true)
                // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/">document</a>
                .setEntityLombokModel(true)
                // Boolean类型字段是否移除is前缀处理
                // .setEntityBooleanColumnRemoveIsPrefix(true)
                // .setRestControllerStyle(true)
                // .setControllerMappingHyphenStyle(true)
        );

        /**
         * 包配置
         */
        gen.setPackageInfo(new PackageConfig()
                        //.setModuleName("User")
                        .setParent(basePackage)// 自定义包路径
                        .setController("controller")// 这里是控制器包名,默认 web
                        .setEntity("model") // 设置Entity包名,默认entity
                        .setMapper("mapper") // 设置Mapper包名,默认mapper
                        .setService("service") // 设置Service包名,默认service
                        .setServiceImpl("service.impl") // 设置Service Impl包名,默认service.impl
                        .setXml("mapper") // 设置Mapper XML包名,默认mapper.xml
                        );

        /**
         * 注入自定义配置
         */
        // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
        InjectionConfig abc = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };
        //自定义文件输出位置(非必须)
        List<FileOutConfig> fileOutList = new ArrayList<FileOutConfig>();
        fileOutList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return canonicalPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        abc.setFileOutConfigList(fileOutList);
        gen.setCfg(abc);

        /**
         * 指定模板引擎 默认是VelocityTemplateEngine ,需要引入相关引擎依赖
         */
        //gen.setTemplateEngine(new FreemarkerTemplateEngine());

        /**
         * 模板配置
         */
        gen.setTemplate(
                // 关闭默认 xml 生成,调整生成 至 根目录
                new TemplateConfig().setXml(null)
                // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
                // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
                // .setController("...");
                // .setEntity("...");
                // .setMapper("...");
                // .setXml("...");
                // .setService("...");
                // .setServiceImpl("...");
        );

        // 执行生成
        gen.execute();
    }
}

###就这样就完成了,是不是很简单的样子,给大家看看我的目录结构
这里写图片描述

###直接运行Generator类中的main方法就行了
这里写图片描述

###这是控制台打印的日志,如果看到这些就表示成功了,然后刷新项目可以看到这些
这里写图片描述

如果有什么问题,可以下载我的案例看看
https://download.csdn.net/download/xiatiancsdn/10608435

MyBatis-Plus 并没有提供直接生成 DTO(Data Transfer Object)的功能,但可以通过自定义代码生成器模板来生成 DTO 类。 首先,你需要配置 MyBatis-Plus 的代码生成器。在 pom.xml(如果是 Maven 项目)或 build.gradle(如果是 Gradle 项目)文件中添加 MyBatis-Plus 依赖: ```xml <!-- Maven --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>latest_version</version> </dependency> ``` ```groovy // Gradle implementation 'com.baomidou:mybatis-plus-generator:latest_version' ``` 然后,在项目中创建一个用于自定义代码生成器的类,例如 `CodeGenerator.java`。在该类中,你可以自定义生成器的配置和模板。 ```java import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; public class CodeGenerator { public static void main(String[] args) { // 1. 全局配置 GlobalConfig globalConfig = new GlobalConfig() .setOutputDir(System.getProperty("user.dir") + "/src/main/java") .setAuthor("YourName") .setOpen(false) .setIdType(IdType.AUTO) .setDateType(DateType.ONLY_DATE) .setServiceName("%sService") .setBaseResultMap(true) .setBaseColumnList(true); // 2. 数据源配置 DataSourceConfig dataSourceConfig = new DataSourceConfig() .setDbType(DbType.MYSQL) .setDriverName("com.mysql.cj.jdbc.Driver") .setUrl("jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai") .setUsername("your_username") .setPassword("your_password"); // 3. 包名配置 PackageConfig packageConfig = new PackageConfig() .setParent("com.example") .setEntity("entity") .setMapper("mapper") .setService("service") .setServiceImpl("service.impl") .setController("controller") .setXml("mapper"); // 4. 策略配置 StrategyConfig strategyConfig = new StrategyConfig() .setNaming(NamingStrategy.underline_to_camel) .setColumnNaming(NamingStrategy.underline_to_camel) .setEntityLombokModel(true) .setRestControllerStyle(true) .setLogicDeleteFieldName("delete_flag") .setEntityTableFieldAnnotationEnable(true) .setControllerMappingHyphenStyle(true) .setEntitySerialVersionUID(true) .setEntityBuilderModel(true) .setEntityTableFieldAnnotationEnable(true); // 5. 模板配置(可根据需求自定义) TemplateConfig templateConfig = new TemplateConfig() .setEntity("/templates/entity.java") .setMapper("/templates/mapper.java") .setService("/templates/service.java") .setServiceImpl("/templates/serviceImpl.java") .setController("/templates/controller.java") .setXml(null); // 6. 执行代码生成器 AutoGenerator autoGenerator = new AutoGenerator() .setGlobalConfig(globalConfig) .setDataSource(dataSourceConfig) .setPackageInfo(packageConfig) .setStrategy(strategyConfig) .setTemplate(templateConfig) .execute(); } } ``` 在上述代码中,你可以根据自己的需求修改全局配置、数据源配置、包名配置、策略配置以及模板配置。模板配置可以根据你的需要自定义生成的代码模板。 最后,运行 `CodeGenerator` 类,即可根据配置生成相应的 DTO 类。生成文件将会出现在指定的包路径下。 希望这可以帮助到你生成 MyBatis-Plus 的 DTO 类!如有任何疑问,请随时提问。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值