Mybatis-Plus 3.5.1版本及以上代码生成器

本文介绍了如何在Spring Boot项目中使用MybatisPlus进行数据库操作,并展示了两种生成代码的不同方式:一种使用FastAutoGenerator配合Freemarker模板,另一种是通过AutoGenerator结合多种策略配置。
摘要由CSDN通过智能技术生成

1:pom.xml

<!--        1:导入数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--        2:导入lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
<!--        3:导入mybatisplus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--velocity模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>com.jslsolucoes</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>
        <!--freemarker模板-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>

2:生成代码

(第一种)

package com.xiaoze;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.Collections;

/**
 * @author 小泽
 * @create 2022-03-10  0:14
 * 记得每天敲代码哦
 */
public class practiceApplication {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatisplus?&serverTimezone=Hongkong", "root", "010429")
                .globalConfig(builder -> {
                    builder.author("小泽") // 设置作者
                            // .enableSwagger() // 开启 swagger 模式
                            .fileOverride() // 覆盖已生成文件
                            .commentDate("yyyy-MM-dd")
                            .outputDir(System.getProperty("user.dir")+"\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("blogs") // 设置父包名
                            .moduleName("systems") // 设置父包模块名
                            .entity("entity")
                            .service("service")
                            .serviceImpl("serviceImpl")
                            .controller("controller")
                            .mapper("mapper")
                            .xml("mapper")
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir")+"\\src\\main\\resources")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("user") // 设置需要生成的表名
                            .addTablePrefix("t_", "c_") // 设置过滤表前缀
                            .serviceBuilder()//1:service策略配置
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder()//2:entity策略配置
                            .enableLombok()
                            .logicDeleteColumnName("deleted")//说明逻辑删除是那个字段
                            // .enableTableFieldAnnotation()  属性加上说明注解
                            .controllerBuilder()//3:controller策略配置
                            .formatFileName("%sController")
                            .enableRestStyle()
                            .mapperBuilder()//4:mapper策略配置
                            .superClass(BaseMapper.class)//继承那个父类
                            .formatMapperFileName("%sMapper")
                            .enableMapperAnnotation()//@mapper开启
                            .formatXmlFileName("%sMapper");//XML名
                })
                 .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }
}

(第二种)

public class CodeGenerator {

    @Test
    public void run() {

        // 1、创建代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 2、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir("E:\\谷粒学院\\guli_parent\\service\\service_edu" + "/src/main/java");

        gc.setAuthor("dyk");
        gc.setOpen(false); //生成后是否打开资源管理器
        gc.setFileOverride(false); //重新生成时文件是否覆盖

        //UserServie
        gc.setServiceName("%sService");	//去掉Service接口的首字母I

        gc.setIdType(IdType.ASSIGN_ID); //主键策略
        gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
        gc.setSwagger2(true);//开启Swagger2模式

        mpg.setGlobalConfig(gc);

        // 3、数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/xiaoze?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("******");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 4、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("eduservice"); //模块名
        //包  com.atguigu.eduservice
        pc.setParent("com.xiaoze");
        //包  com.atguigu.eduservice.controller
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 5、策略配置
        StrategyConfig strategy = new StrategyConfig();

        strategy.setInclude("edu_course","edu_course_description","edu_chapter","edu_video");

        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀

        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
        strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
        strategy.setChainModel(true);  //  @Accessors(chain = true) setter链式操作

        strategy.setRestControllerStyle(true); //restful api风格控制器
        strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符

        mpg.setStrategy(strategy);

        // 6、执行
        mpg.execute();
    }
}

MyBatis-Plus 3.5.1 代码生成器MyBatis-Plus 框架提供的一款代码生成工具,可以帮助开发者快速生成 MyBatis-Plus 的 Mapper 接口及其 XML 映射文件、Service 接口、ServiceImpl 实现类、Entity 实体类等代码。 使用 MyBatis-Plus 代码生成器,可以减轻开发者的工作负担,提高开发效率,避免手写重复性的代码。以下是使用 MyBatis-Plus 代码生成器的步骤: 1. 引入 MyBatis-Plus 依赖 在项目的 pom.xml 文件中,添加 MyBatis-Plus 的依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.5.1</version> </dependency> ``` 2. 配置代码生成器 在项目的配置文件(如 application.yml 或 application.properties)中,添加代码生成器的配置信息,包括数据库连接信息、生成代码的包路径、作者等信息。 ``` mybatis-plus: global-config: db-config: # 数据库配置 url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true username: root password: 123456 driver-name: com.mysql.cj.jdbc.Driver generator: # 生成代码的包路径 package-name: com.example.mybatisplusdemo # 生成代码的作者 author: example # 开启生成器 enable: true # 开启实体类 Lombok 注解 enable-lombok: true # 开启 Swagger2 注解 enable-swagger: true # 开启 ActiveRecord 模式(生成 ActiveRecord 的实体类和接口) enable-activerecord: true ``` 3. 运行代码生成器 在项目的启动类中,添加以下代码,启动代码生成器: ``` @SpringBootApplication public class MybatisPlusDemoApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusDemoApplication.class, args); // 启动代码生成器 MybatisPlusGenerator.execute(); } } ``` 4. 查看生成代码 代码生成器会根据配置信息,自动生成 Mapper 接口及其 XML 映射文件、Service 接口、ServiceImpl 实现类、Entity 实体类等代码生成代码位于指定的包路径下。开发者可以在生成代码的基础上,进行业务代码的开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小泽不会Java

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

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

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

打赏作者

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

抵扣说明:

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

余额充值