什么是Mybatis Plus?
Mybatis Plus是一个基于Mybatis框架的轻量级代码生成器,它提供了许多实用的功能,大大简化了开发过程。Mybatis Plus可以与Spring Boot等流行的Java框架无缝集成,使得开发者可以更加高效地进行数据库操作。
AutoGenerator——简化代码生成过程
AutoGenerator是Mybatis Plus最新的代码生成器,它有着更加简洁的API,帮助开发者更轻松地生成代码。我们来看一下AutoGenerator的用法。
首先,我们需要引入Mybatis Plus和AutoGenerator的依赖。在项目的pom.xml文件中添加如下依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>最新版本</version>
</dependency>
然后,在项目的配置文件application.properties或application.yml中配置数据库连接信息,例如:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: root
接下来,我们可以开始使用AutoGenerator来生成代码了。首先,我们创建一个主函数,然后编写以下代码段:
public class Generator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("your name");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("your module name");
pc.setParent("com.example");
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setController(null); // 不生成Controller层代码
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude("table_name"); // 生成指定表的代码,多个表用逗号分隔
mpg.setStrategy(strategy);
mpg.execute();
}
}
以上代码中,我们可以根据需要修改输出路径、作者名、模块名、包名、数据库连接信息、生成的表等配置。如果不需要生成Controller层代码,可以注释掉templateConfig.setController(null);一行。
最后,运行主函数,代码生成器将自动生成实体类、Mapper接口、Service类等代码文件,并放置在指定的包路径下。
结语
Mybatis Plus的AutoGenerator代码生成器大大简化了代码编写的过程,提高了开发效率。开发者只需要配置一些基本信息,便可自动生成常用的代码文件,大大减少了重复劳动。赶快尝试一下吧!

评论 (0)