MyBatis-Plus代码生成器的使用自动生成Mapper Service Entity类

MyBatis-Plus 代码生成器的使用(生成mapper,service,entity)

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

官方文档教程

1.第一步导入相关依赖

<!-- mybatis-plus 和springboot整合包 -->
<dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.1.0</version>
</dependency>
<!-- 代码生成器 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.3.1.tmp</version>
</dependency>
<!-- 添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎 -->
<dependency>
     <groupId>org.freemarker</groupId>
     <artifactId>freemarker</artifactId>
     <version>2.3.29</version>
</dependency>

2.编辑代码生成器

package com.lijia;

import java.util.Scanner;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

/**
 * @Description
 * @Author lijia
 * @Date 2020/2/13 18:29
 */
public class CodeGenerator {

    //项目的真实路径
    private static final String PROJECT_RELATIVE_PATH="D:/work/android_demo";
    
    // 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Veloctiy
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        // 全局配置

        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(PROJECT_RELATIVE_PATH+"/src/main/java");    //生成文件的输出目录
        gc.setAuthor("lijia");                    //作者
        gc.setFileOverride(true);                //是否覆蓋已有文件 默认值:false
        gc.setOpen(false);                        //是否打开输出目录 默认值:true
        //gc.setSwagger2(true);                    //开启 swagger2 模式 默认false
        gc.setBaseColumnList(true);                //开启 baseColumnList 默认false
        gc.setBaseResultMap(true);                //开启 BaseResultMap 默认false
        gc.setEntityName("%s");            //实体命名方式  默认值:null 例如:%sEntity 生成 UserEntity
        gc.setMapperName("%sMapper");            //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
        gc.setXmlName("%sMapper");                //Mapper xml 命名方式   默认值:null 例如:%sDao 生成 UserDao.xml
        gc.setServiceName("%sService");            //service 命名方式   默认值:null 例如:%sBusiness 生成 UserBusiness
        gc.setServiceImplName("%sServiceImpl");    //service impl 命名方式  默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
        gc.setControllerName("%sController");    //controller 命名方式    默认值:null 例如:%sAction 生成 UserAction
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);        //数据库类型	该类内置了常用的数据库类型【必须】
        //mysql 8.0.3以上 加上serverTimezone=UTC
        dsc.setUrl("jdbc:mysql://localhost:3306/db_android?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("1234");
        mpg.setDataSource(dsc);

        // 包配置
        //设置各个包路径
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent("com.lijia"); //设置父包
        //pc.setEntity() //如果不给各个模块设置具体的包路径,则默认是
        //pc.setXml("resources.mapper");//不设置的话 默认是和java类在一起
        mpg.setPackageInfo(pc);

        // 自定义配置
/*	        InjectionConfig cfg = new InjectionConfig() {
	            @Override
	            public void initMap() {		//注入自定义 Map 对象
	                // to do nothing
	            }
	        };
	        List<FileOutConfig> focList = new ArrayList<>();
	        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
	            @Override
	            public String outputFile(TableInfo tableInfo) {
	                // 自定义输入文件名称
	                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
	                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
	            }
	        });
	        cfg.setFileOutConfigList(focList);
	        mpg.setCfg(cfg);
	        mpg.setTemplate(new TemplateConfig().setXml(null));*/

        // 策略配置	数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);    //表名生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行


/*        strategy.setCapitalMode(true);            // 全局大写命名 ORACLE 注意
        strategy.setTablePrefix("prefix");        //表前缀
        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");    //自定义继承的Entity类全称,带包名
        strategy.setSuperEntityColumns(new String[]{"test_id", "age"});    //自定义实体,公共字段
        strategy.setEntityLombokModel(true);    //【实体】是否为lombok模型(默认 false
        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");    //自定义继承的Controller类全称,带包名*/


        //如果不设置  默认是 包含全部表
        //strategy.setInclude(scanner("表名"));		//需要包含的表名,允许正则表达式(与exclude二选一配置)
        //strategy.setInclude(new String[] { "user" }); // 需要生成的表可以多张表
        //strategy.setExclude(new String[]{"test"}); // 排除生成的表

        strategy.setRestControllerStyle(true); //controller 层使用Restful风格
        strategy.setControllerMappingHyphenStyle(true);    //驼峰转连字符
        strategy.setTablePrefix("tb_");    //去掉前缀
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

3. 接下来大功告成

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis-Plus代码生成器是一个非常方便的工具,可以帮助我们快速生成MyBatis相关的代码。而Velocity则是一个模板引擎,可以帮助我们更加方便地生成代码模板。 下面是使用MyBatis-Plus代码生成器与Velocity一起使用的步骤: 1. 准备好Velocity模板文件,可以参考MyBatis-Plus官方提供的模板,也可以根据自己的需求编写模板。 2. 在MyBatis-Plus代码生成器的配置文件中,添加Velocity的配置,例如: ```xml <strategyConfig> <templateConfig> <controller>templates/velocity/controller.java.vm</controller> <service>templates/velocity/service.java.vm</service> <serviceImpl>templates/velocity/serviceImpl.java.vm</serviceImpl> <mapper>templates/velocity/mapper.java.vm</mapper> <entity>templates/velocity/entity.java.vm</entity> </templateConfig> </strategyConfig> ``` 这里我们配置了使用Velocity的模板文件路径。 3. 在Velocity模板文件中,使用Velocity的语法编写模板,可以根据需要添加参数,例如: ```velocity package ${package_name}.service.impl; import ${package_name}.entity.${table_name}; import ${package_name}.mapper.${table_name}Mapper; import ${package_name}.service.I${table_name}Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * ${table_comment} 服务实现 * </p> */ @Service public class ${table_name}ServiceImpl extends ServiceImpl<${table_name}Mapper, ${table_name}> implements I${table_name}Service { } ``` 这里我们使用了Velocity的语法来获取参数,并且根据模板生成对应的代码。 4. 最后,在MyBatis-Plus代码生成器中运行生成器,就可以生成对应的代码了。 总的来说,使用MyBatis-Plus代码生成器与Velocity一起使用,可以帮助我们更加方便地生成MyBatis相关的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

54hake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值