导入相关依赖
MyBatis-Plus的依赖
<!--mybatis-plus启动依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
- MyBatis官方文档网站
- Maven中央仓库网址
- 可以到Maven中央网站,搜索MyBatis-Plus依赖,找使用数量较大的使用
MyBatis-Plus代码生成器(新)的依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.7</version>
</dependency>
注意
全新的代码生成器添加于 3.5.1 版本,且对历史版本不兼容!如果您用的是 3.5.1 以下的版本,请参考 代码生成器 进行配置与使用。
使用代码生成器(官方代码)
1、在数据库中建立一张表
2、创建CodeGenerator.java
public static void main(String[] args) {
FastAutoGenerator.create("url", "username", "password")
.globalConfig(builder -> {
builder.author("baomidou") // 设置作者
.enableSwagger() // 开启 swagger 模式
.outputDir("D://"); // 指定输出目录
})
.dataSourceConfig(builder ->
builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
if (typeCode == Types.SMALLINT) {
// 自定义类型转换
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
})
)
.packageConfig(builder ->
builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
.moduleName("system") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")) // 设置mapperXml生成路径
)
.strategyConfig(builder ->
builder.addInclude("t_simple") // 设置需要生成的表名
.addTablePrefix("t_", "c_") // 设置过滤表前缀
)
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
在SpringBoot项目使用
使代码生成器类读取application.yml中的数据库配置
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
在MyCodeGeneratorTest类(用来代码生成的类)上添加注解
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = MyCodeGeneratorTest.class)
- @ActiveProfiles(“dev”) // 指定application-dev.yml文件
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyCodeGeneratorTest.class)
@ActiveProfiles("dev")
public class MyCodeGeneratorTest {
@Value("${application中的数据库url配置}")
private String url;
@Value("${application中的数据库username配置}")
private String username;
@Value("${application中的数据库password配置}")
private String password;
// 生成代码的绝对路径
private String getGeneratorPath() {
try {
String resourcePath = this.getClass().getClassLoader().getResource("").getPath();
File generatorDirs = new File(resourcePath + "/" + "generatorFiles");
if (!generatorDirs.exists()) {
generatorDirs.mkdirs();
}
log.info("生成代码输出位置:" + generatorDirs.getAbsolutePath());
return generatorDirs.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Test
public void quickGenerator() {
String generatorPath = getGeneratorPath();
if (generatorPath == null) {
log.info("生成输出目录失败");
return;
}
// 你的数据库表名
String tableName = "sys_user";
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> {
builder.author("baomidou") // 设置作者
// .enableSwagger() // 开启 swagger 模式
.outputDir(generatorPath); // 指定输出目录
})
.dataSourceConfig(builder ->
builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
if (typeCode == Types.SMALLINT) {
// 自定义类型转换
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
})
)
.packageConfig(builder ->
builder.parent("com.baomidou.mybatisplus.samples.generator") // 设置父包名
// .moduleName("takeaway-system") // 设置父包模块名(微服务可能会使用)
.pathInfo(Collections.singletonMap(OutputFile.xml, generatorPath)) // 设置mapperXml生成路径
)
.strategyConfig(builder ->
builder.addInclude(tableName) // 设置需要生成的表名
.addTablePrefix("t_", "c_") // 设置过滤表前缀
)
// .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
交互式代码生成
public void generator2() {
String generatorPath = getGeneratorPath();
if (generatorPath == null) {
log.info("生成输出目录失败");
return;
}
FastAutoGenerator.create(url, username, password)
// 全局配置
.globalConfig((scanner, builder) -> {
builder.author("baomidou")
.outputDir(generatorPath); // 指定输出目录
}
)
// 数据库连接配置
.dataSourceConfig(builder ->
builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
int typeCode = metaInfo.getJdbcType().TYPE_CODE;
if (typeCode == Types.SMALLINT) {
// 自定义类型转换
return DbColumnType.INTEGER;
}
return typeRegistry.getColumnType(metaInfo);
})
)
// 包配置
.packageConfig((scanner, builder) -> {
String moduleName = scanner.apply("输入模块名称: system/business");
builder.parent("com.takeaway." + moduleName)
.pathInfo(Collections.singletonMap(OutputFile.xml, generatorPath)) // 设置mapperXml生成路径
;
})
// 策略配置
.strategyConfig((scanner, builder) -> {
builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.entityBuilder()
.enableColumnConstant() // 开启生成字段常量
// .enableLombok()
.addTableFills(
new Column("create_time", FieldFill.INSERT)
)
.build();
// Controller配置
builder.controllerBuilder()
.enableRestStyle(); // 开启生成@RestController 控制器(包含里@ResponseBody和@Controller)
// mapper配置
builder.mapperBuilder()
.enableBaseResultMap() //启用 BaseResultMap 生成
.enableBaseColumnList() // 启用 BaseColumnList
.build();
}
)
// 使用Freemarker引擎模板,默认的是Velocity引擎模板
// .templateEngine(new FreemarkerTemplateEngine())
.execute();
}
// 处理 all 情况
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}