【Springboot】【Mybatis-Plus】AutoGenerator 代码生成器使用

在这里插入图片描述

前言

本节讲述 mybatis-plus 的 AutoGenerator 代码生成器的使用。

内容包括项目创建,依赖配置,数据库创建,和编码。

注:MyBatis-Plus (MP) 是一个基于 MyBatis 的强大且易用的持久层框架扩展,旨在简化 MyBatis 的使用,提高开发效率,并提供了一系列强大的特性。 MyBatis-Plus 特性:

  1. 无侵入式设计:MyBatis-Plus 在保留 MyBatis 原有功能的基础上进行扩展,不需要对原有代码进行大量修改,可以无缝集成到现有的 MyBatis 项目中。
  2. 自动 CRUD 操作:MyBatis-Plus 提供了基础的增删改查操作的自动化支持,只需通过简单的配置和注解,就可以实现对数据库的基本操作。
    条件构造器:MyBatis-Plus 提供了一个强大的条件构造器,可以方便地构建复杂的 SQL 查询语句,无需手动编写 SQL。
  3. 动态表名/列名:支持在运行时动态指定表名和列名,这对于处理多租户或者数据分片等场景非常有用。
  4. 逻辑删除:MyBatis-Plus 提供了逻辑删除的支持,可以通过设置一个字段值来标记数据是否被删除,而不是物理删除数据。
  5. 分页插件:内置了分页插件,可以方便地实现分页查询,支持多种数据库的分页方式。
  6. 性能分析插件:提供了性能分析插件,可以帮助开发者了解 SQL 执行的性能情况,便于优化 SQL 查询。
  7. 代码生成器:MyBatis-Plus 提供了一个强大的代码生成器,可以根据数据库表结构自动生成对应的实体类、Mapper 接口和 XML 映射文件,极大地提高了开发效率。
  8. 通用 CRUD 操作:提供了通用的 CRUD 操作接口,可以减少重复代码的编写,提高代码复用率。
  9. 全局拦截器:支持自定义全局拦截器,可以在执行 SQL 之前或之后添加自定义的逻辑。

前置准备

我这里随便用一个untitled项目,新创建一个Module:
在这里插入图片描述
module 命名为 mybatis-plus-generator
在这里插入图片描述

创建 application.properties:

server.port=8080

## if savebatch, could try rewriteBatchedStatements=true setting postgres/123456
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/postgres?stringtype=unspecified  # 我这里用本地数据库
spring.datasource.username=你的数据库账号
spring.datasource.password=你的数据库密码
spring.datasource.driver-class-name=org.postgresql.Driver
#spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

#
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

创建 MainApplication.java

package org.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
@MapperScan("org.sample.dao.mapper")
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

打开某个数据库平台(我这里是DBeaver),连接本地数据库,创建一个新scheme:

在这里插入图片描述

我命名为generator:

在这里插入图片描述

创建一个名为 image_info 的数据表:

CREATE TABLE generator.image_info (
	id serial NOT NULL,
	image_name text NOT NULL,
	image_uuid_address text NOT NULL,
	encoded_image text NOT NULL,
	image_owner text NOT NULL,
	allow_download_times int8 NULL DEFAULT 10,
	authorized_user _varchar NULL,
	is_deleted int8 NOT NULL,
	"version" int8 NOT NULL DEFAULT 0,
	create_time timestamptz NULL,
	create_user text NULL,
	update_time timestamptz NULL DEFAULT now(),
	update_user text NULL,
	CONSTRAINT image_info_pkey PRIMARY KEY (id)
);

-- Column comments

COMMENT ON COLUMN generator.image_info.image_name IS '图片文件全名';
COMMENT ON COLUMN generator.image_info.image_uuid_address IS '图片UUID地址(加密)';
COMMENT ON COLUMN generator.image_info.encoded_image IS '图片MD5编码';
COMMENT ON COLUMN generator.image_info.image_owner IS '图片所有人';
COMMENT ON COLUMN generator.image_info.allow_download_times IS '图片允许的下载次数';
COMMENT ON COLUMN generator.image_info.authorized_user IS '下载或预览的授权用户';
COMMENT ON COLUMN generator.image_info."version" IS '乐观锁版本号';
COMMENT ON COLUMN generator.image_info.create_time IS '创建时间';
COMMENT ON COLUMN generator.image_info.create_user IS '创建人';
COMMENT ON COLUMN generator.image_info.update_time IS '修改时间';
COMMENT ON COLUMN generator.image_info.update_user IS '修改人';

在这里插入图片描述

项目实现

创建一个名为 config 的目录

在这里插入图片描述

在config目录中创建CodeGenerator.java

package org.sample.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Scanner;

public class CodeGenerator {

    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.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator autoGenerator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        // 代码生成路径
        globalConfig.setOutputDir(projectPath + "/mybatis-plus-generator" + "/src/main/java");
        // 是否覆盖以前文件
        globalConfig.setFileOverride(false);
        // 是否打开生成目录
        globalConfig.setOpen(false);
        // 设置项目作者
        globalConfig.setAuthor("test");
        // 主键策略
        globalConfig.setIdType(IdType.AUTO);
        // 生成基本ResultMap
        globalConfig.setBaseResultMap(true);
        // 生成基本ColumeList
        globalConfig.setBaseColumnList(true);
        // 去掉服务默认前缀
        globalConfig.setServiceName("%sService");
        // 设置时间类型
        globalConfig.setDateType(DateType.ONLY_DATE);
        autoGenerator.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        // 数据库类型
        dataSourceConfig.setDbType(DbType.POSTGRE_SQL);
        dataSourceConfig.setUrl("jdbc:postgresql://127.0.0.1:5432/postgres?stringtype=unspecified&useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8");
        dataSourceConfig.setDriverName("org.postgresql.Driver");
        dataSourceConfig.setUsername("你的账号");
        dataSourceConfig.setPassword("你的密码");
        dataSourceConfig.setSchemaName("generator");
        autoGenerator.setDataSource(dataSourceConfig);

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
//        packageConfig.setModuleName("xxxx");
        packageConfig.setParent("org.sample");
        packageConfig.setMapper("dao.mapper");
        packageConfig.setXml("mapper");
        packageConfig.setEntity("dao.entity");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setController("controller");
        autoGenerator.setPackageInfo(packageConfig);

        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        // 包的命名规则,使用驼峰规则
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        // 列的名称,使用驼峰规则
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        // 自动lombok
        strategyConfig.setEntityLombokModel(true);
        strategyConfig.setRestControllerStyle(true);
        // 驼峰命名
        strategyConfig.setControllerMappingHyphenStyle(true);
        // 设置逻辑删除,前提是表中有"deleted"字段
        strategyConfig.setLogicDeleteFieldName("deleted");
        // 设置自动填充配置,在项目开发过程中,例如创建时间,修改时间,每次,都需要我们来指定,太麻烦了,设置为自动填充规则,就不需要我们赋值
        // 前提是表中有"create_time"字段, 有"update_time"字段
        TableFill create_time = new TableFill("create_time", FieldFill.INSERT);
        TableFill update_time = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(create_time);
        tableFills.add(update_time);
        strategyConfig.setTableFillList(tableFills);
        // 乐观锁, 前提是表中有"version"字段
        strategyConfig.setVersionFieldName("version");
        // 设置表名前缀
        strategyConfig.setInclude(scanner("表名,多个英文逗号分割").split(","));
        // 给 entity 添加 TableField 注解
        strategyConfig.setEntityTableFieldAnnotationEnable(true);
        autoGenerator.setStrategy(strategyConfig);


        // 生成代码
        autoGenerator.execute();
    }
}

其中 scanner () 用于从控制台获取用户输入。如果用户未输入或输入为空,则抛出异常。

main 方法中主要创建 AutoGenerator 对象,这是 MyBatis-Plus 的代码生成器,随后配置全局配置(GlobalConfig):

  1. 设置代码生成的输出目录。
  2. 设置是否覆盖已存在的文件。
  3. 设置是否在生成代码后打开生成目录。
  4. 设置项目作者。
  5. 设置主键策略为自动增长。
  6. 设置生成基本的 ResultMap 和 ColumnList。
  7. 去掉服务默认前缀。
  8. 设置日期类型为只包含日期部分。

配置数据源配置(DataSourceConfig):

  1. 设置数据库类型为 PostgreSQL。
  2. 设置数据库连接 URL、驱动名、用户名和密码。
  3. 设置默认的模式名为 “generator”。

配置包配置(PackageConfig):

  1. 设置父包名称为 “org.sample”。
  2. 设置各个模块的包名,如 DAO、实体类、服务接口、服务实现和控制器等。

配置策略配置(StrategyConfig):

  1. 设置命名规则,包括表名和列名的驼峰命名。
  2. 开启 Lombok 自动注解。
  3. 设置RestController风格的控制器。
  4. 设置路径中的连字符样式。
  5. 设置逻辑删除字段为 “deleted”。
  6. 设置自动填充规则,包括创建时间和更新时间的自动填充。
  7. 设置乐观锁版本字段为 “version”。
  8. 设置要包含的表名列表,通过控制台输入多个表名并用逗号分隔。
  9. 开启为实体类添加 TableField 注解。

最后,调用 autoGenerator.execute() 方法执行代码生成。

运行

运行CodeGenerator.java
在这里插入图片描述
在命令行中输入表名 image_info,键入:

在这里插入图片描述

在dao.entity.ImageInfo中,可以看到自增id主键
在这里插入图片描述

乐观锁

在这里插入图片描述

时间插入设置

在这里插入图片描述

可以注意到,表名不包含前面的scheme,我们可以手动修改image_infogenerator.image_info

在这里插入图片描述

总结

通过运行这段代码,可以根据配置自动生成与指定数据库表对应的 Java 持久层代码,大大提高了开发效率。在运行前需要修改数据源配置中的数据库连接信息以及表名列表。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

锥栗

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

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

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

打赏作者

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

抵扣说明:

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

余额充值