使用 MyBatis-Plus 代码生成器生成代码

在项目当中,如 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,重复去创建很繁琐,我们可以通过程序自动生成的,提升我们开发的效率。这篇文章记录如何使用 MyBatis-Plus 的代码生成器,生成代码,减少我饿们重复性劳动。下面给出一个可行的参考代码,具体的步骤可以参考官网文档

@SpringBootTest(classes = DistributedLockApp.class)
@RunWith(SpringRunner.class)
@Slf4j
public class CodeGenerate {

    @Autowired
    private DataSourceProperties dataSource;

    /**
     * 项目路径
     */
    private static final String projectPath = System.getProperty("user.dir");

    /**
     * 要生成的表名称
     */
    private static final String tableNames = "actor,address,category,city,country," +
            "customer,film,film_actor,film_category,film_text,inventory,language,payment,rental,staff,store";

    @Test
    public void generate() {
        //最终的代码生成
        config().execute();
    }

    private AutoGenerator config() {
        AutoGenerator generator = new AutoGenerator()
                .setDataSource(getDataSourceConfig())
                .setGlobalConfig(getGlobalConfig())
                .setStrategy(getStrategyConfig())
                .setPackageInfo(getPackageConfig())
                .setTemplate(getTemplateConfig())
                //设置模板引擎
                .setTemplateEngine(new FreemarkerTemplateEngine())
                .setCfg(getInjectionConfig());
        return generator;
    }


    /**
     * 数据源配置:连接数据库
     */
    private DataSourceConfig getDataSourceConfig() {
        return new DataSourceConfig().
                setUrl(dataSource.getUrl())
                .setDriverName(dataSource.getDriverClassName())
                .setUsername(dataSource.getUsername())
                .setPassword(dataSource.getPassword());
    }

    /**
     * 全局信息设置:设置文件输出路径、作者信息、是否覆盖文件等
     */
    private GlobalConfig getGlobalConfig() {
        final String outPutDir = projectPath + "/src/main/java";
        final String author = "kpq";
        GlobalConfig globalConfig = new GlobalConfig()
                .setOutputDir(outPutDir).setAuthor(author)
                //是否打开输出目录
                .setOpen(false).setSwagger2(false).setBaseResultMap(false)
                //是否覆盖已有的文件,设置service实现类的名称
                .setFileOverride(false).setServiceImplName("%sService");
        return globalConfig;
    }

    /**
     * 生成包名设置
     */
    private PackageConfig getPackageConfig() {
        //父级目录
        final String parentPath = "com.example.distributedLock";
        //设置service实现类所在的包名
        final String servicePackage = "service";
        PackageConfig packageConfig = new PackageConfig()
                .setParent(parentPath).setModuleName("").setService("")
                .setServiceImpl(servicePackage);
        return packageConfig;
    }

    /**
     * 策略配置
     */
    private StrategyConfig getStrategyConfig() {
        //实体类要继承的超类
        final String superEntityClass = "com.example.distributedLock.entity.base.BaseEntity";
        //超类当中的字段
        final String superEntityColumns = "last_update";
        StrategyConfig strategy = new StrategyConfig()
                .setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setSuperEntityClass(superEntityClass)
                .setSuperEntityColumns(superEntityColumns)
                .setEntityLombokModel(true)
                .setInclude(tableNames.split(","));
        return strategy;
    }

    /**
     * 模板配置:配置自定义模板
     */
    private TemplateConfig getTemplateConfig() {
        TemplateConfig templateConfig = new TemplateConfig()
                .setXml(null).setService("").setController("")
                .setServiceImpl("templates/customizeServiceImpl.java");
        return templateConfig;
    }

    private InjectionConfig getInjectionConfig() {
        final String templatePath = "/templates/mapper.xml.ftl";
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };

        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return projectPath + "/src/main/resources/mapper/" + getPackageConfig().getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

}

最终结果:

主要原理

MyBatis-Plus 为我们提供了一系列模板,通过填充模板生成我们想要的代码,如下图所示。如果模板不符合需求,我们也可以自定义自己的模板来生成所需的代码。

个人博客:https://www.kangpeiqin.cn/#/index
欢迎与我交流,关注公众号(sunny的技术小屋),获取更多技术相关知识

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值