Mybatis-Plus 新版代码生成器使用

673 阅读4分钟

Mybatis-Plus 新版代码生成器的使用

作为一名散装java小白,以前不太喜欢看别人的官方文档,喜欢直接去百度别人写好的教程,现在发现官方文档也挺不错,给MP点赞。第一次写东西,请大家多多指教。

回归正题

一、引入依赖

<!--mybatis-plus依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<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>
<!--使用Freemarker引擎模板,默认的是Velocity引擎模板-->
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

二、编写配置文件

server:
  port: 8080
spring:
  application:
    name: mybatis-plus
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mall_tiny?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

mybatis-plus:
  type-aliases-package: com.example.mybatisplusgenerator.entity
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

注意:如果mysql依赖是通过idea新建-项目-Spring Initializr点击依赖选项生成的,需要在application.yml配置文件里,数据源url添加: &useSSL=false ,driver-class-name修改为:com.mysql.cj.jdbc.Driver,否则会报错,这里的原因是因为:使用上面方式引入的mysql依赖是8.0,而MySQL在高版本需要指明是否进行SSL连接。

   SSL协议提供服务主要: 		
       1)认证用户服务器,确保数据发送到正确的服务器;    .
       2)加密数据,防止数据传输途中被窃取使用;
       3)维护数据完整性,验证数据在传输过程中是否丢失;

   当前支持SSL协议两层:
   	 	SSL记录协议(SSL Record Protocol):建立靠传输协议(TCP)高层协议提供数据封装、压缩、加密等基本功能支持
	    SSL握手协议(SSL Handshake Protocol):建立SSL记录协议用于实际数据传输始前通讯双进行身份认证、协商加密
	    算法、 交换加密密钥等。

image.png

第二种解决方式:

原先idea生成的

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

替换指定mysql为低版本

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>

三、编写代码生成器类

public class FastAutoGeneratorTest {

    /**
     * 执行 run
     */
    public static void main(String[] args) {
        //1、配置数据源
// 《=============================需要修改的地方================================》
        com.baomidou.mybatisplus.generator.FastAutoGenerator.create("jdbc:mysql://localhost:3306/mall_tiny?tinyInt1isBit=false&serverTimezone=GMT%2B8", "root", "123456")
                //2、全局配置
                .globalConfig(builder -> {
                    builder
                            //(重要)覆盖已生成文件,谨慎配置,开启后是整个文件夹覆盖替换,此时建议开启设置父包模块名.moduleName("")
                            .fileOverride()
                            /*(重要)指定输出目录
                                 指定输出目录,springboot项目可以使用如下方式,相对目录,自动生成当前项目目录
                                .outputDir(System.getProperty("user.dir") + "/src/main/java")
                             */
// 《=============================需要修改的地方================================》
                            .outputDir("E:\work\mybatis-plus-generator\src\main\java\")
                            // 设置作者
                            .author("cc")
                            //开启 swagger 模式
                            .enableSwagger()
                            //(重要)时间类型,看你喜欢用sql包中的Date、util包中的Date还是更新的LocalDateTime
                            .dateType(DateType.TIME_PACK)
                            // 注释日期的格式
                            .commentDate("yyyy-MM-dd");
                })
                //3、包配置
                .packageConfig(builder -> {
                    builder
// 《=============================需要修改的地方================================》
                            // 设置父包名
                            .parent("com.example.mybatisplusgenerator")
                            // 设置父包模块名 .moduleName("system")
                            .moduleName("role")
                            //Entity 包名
                            .entity("entity")
                            //Service 包名
                            .service("service")
                            //Service Impl 包名
                            .serviceImpl("service.impl")
                            //Mapper 包名
                            .mapper("mapper")
                            //Mapper XML 包名
                            .xml("mapper.xml")
                            //Controller 包名
                            .controller("controller")
                            //自定义文件包名,输出自定义文件时所用到的包名
                            .other("other")
                            //路径配置信息
// 《=============================需要修改的地方================================》
                            .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\work\mybatis-plus-generator\src\main\resources\mapper")); // 设置mapperXml生成路径
                })
                //4、策略配置
                .strategyConfig(builder -> {
                    builder
// 《=============================需要修改的地方================================》
                            // 设置需要生成的表名
                            .addInclude("ums_role","mus_resource")
                            // 设置过滤表前缀
                            .addTablePrefix("t_", "ums_")
                            // 跳过视图的生成
                            .enableSkipView()
                            //Entity 策略配置
                            .entityBuilder()
                            // (重要)主键模式,这里设置自动模式,配合mysql的自增主键
                            .idType(IdType.ASSIGN_ID)
                            //开启 lombok 模型
                            .enableLombok()
                            //开启生成实体时生成字段注解
                            .enableTableFieldAnnotation()
                            // entity文件名,这里配置后面统一加Entity后缀
                            .formatFileName("%sEntity")
                            //service 策略配置
                            .serviceBuilder()
                            .formatServiceFileName("%sService")
                            // activeRecord模式,使用上来说就是
                            // 可以直接在entity对象上执行insert、update等操作
                            //.enableActiveRecord()
                            //Mapper 策略配置
                            .mapperBuilder()
                            //开启 @Mapper 注解
                            .enableMapperAnnotation()
                            //启用 BaseResultMap 生成
                            .enableBaseResultMap()
                            //启用 BaseColumnList


                            .enableBaseColumnList()
                            //Controller 策略配置
                            .controllerBuilder()
                            //开启驼峰转连字符
                            .enableHyphenStyle()
                            //开启生成@RestController 控制器
                            .enableRestStyle();


                })
                // 5、使用Freemarker引擎模板,默认的是Velocity引擎模板
                .templateEngine(new FreemarkerTemplateEngine())
                // 6、执行
                .execute();

    }

运行FastAutoGeneratorTest即可生成对应的类。

想要自由度更高的生成需要的类,这个目前还不会,好像需要从mybatis-plus的依赖包里复制出来一些模板,具体使用还不会。