Springboot项目整合Mybatis-plus如何使用代码生成器以velocity为模板自动生成代码

在mybatis-plus中,可以使用模板来进行代码的自动生成,在mybatis-plus中默认使用的模板是velocity模板,下面就以这个模板作为例子来演示如何进行代码的自动生产。

使用步骤:

1、添加依赖

<!--        代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
<!--        velocity模板引擎-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

2、新建一个类,并给出一个main方法:

在这里插入图片描述

3、根据需求设置参数

public static void main(String[] args) {

        AutoGenerator autoGenerator = new AutoGenerator();

        DataSourceConfig dataSource = new DataSourceConfig();
        dataSource.setDriverName(数据库连接); //MySql为com.mysql.cj.jdbc.Driver
        dataSource.setUrl(连接地址); //jdbc:mysql://localhost:3306/数据库名称?serverTimezone=UTC
        dataSource.setUsername(数据库连接名);
        dataSource.setPassword(数据库连接密码);
        autoGenerator.setDataSource(dataSource);

        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir")+"/***/src/main/java") //生成文件的路径,默认生成到D盘根目录,{***}处为Module的名称
                .setOpen(false) //生成后是否打开所在的目录
                .setAuthor("****")          //设置代码的作者
                .setFileOverride(true)      //是否覆盖原文件
                .setMapperName("%sMapper")      //设置Mapper文件名,%s为占位符
                .setIdType(IdType.ASSIGN_ID);           //ID生成策略
        autoGenerator.setGlobalConfig(globalConfig);

        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example")   //设置所在的包
                .setEntity("entity")            //设置所在的实体类包名
                .setMapper("mapper");           //设置数据层包名
        autoGenerator.setPackageInfo(packageConfig);

//        在mybatis-plus中默认使用velocity,所以此处不用配置
//        autoGenerator.setTemplateEngine();
//        autoGenerator.setTemplate();

        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setInclude("tb_book","tb_order")    //需要生成的表,这里是可变参数,中间中逗号隔开
                .setTablePrefix("tb_")              //表的前缀
                .setRestControllerStyle(true)           //是否启用Rest风格
                .setVersionFieldName("version")         //乐观锁的字段名
                .setLogicDeleteFieldName("deleted")         //逻辑删除字段名
                .setEntityLombokModel(true);        //是否启用lombok
        autoGenerator.setStrategy(strategyConfig);

        autoGenerator.execute();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值