springboot 整合 mybatisplus最新版 代码生成指定生成模版
时间: 2025-02-02 13:02:29 浏览: 36
### 整合 MyBatis Plus 并自定义代码生成模板
#### 配置依赖项
为了在 Spring Boot 中整合 MyBatis Plus 的最新版本,需更新 `pom.xml` 文件中的依赖关系。确保引入了最新的 MyBatis Plus 和其代码生成器模块。
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
<!-- 用于代码生成 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${latest.version}</version>
</dependency>
```
#### 自定义代码生成策略
通过继承 `DefaultGeneratorTemplate` 或者实现 `IGeneratorStrategy` 接口来自定义代码生成逻辑。可以创建一个新的类来覆盖默认行为并设置特定于项目的模板路径:
```java
public class CustomGenerationStrategy extends DefaultGeneratorTemplate {
@Override
protected void init() {
super.init();
// 设置全局配置属性
GlobalConfig globalConfig = new GlobalConfig.Builder()
.outputDir("src/main/java") // 输出目录
.author("Your Name") // 开发人员名称
.fileOverride(true) // 是否覆盖已有文件
.build();
this.setGlobalConfig(globalConfig);
// 定义包结构
PackageConfig packageConfig = new PackageConfig.Builder()
.parent("com.example.project")
.moduleName("module-name")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "src/main/resources/mapper"))
.build();
this.setPackageInfo(packageConfig);
// 使用自定义模板位置
TemplateConfig templateConfig = new TemplateConfig.Builder()
.entity("/templates/entity.java.vm") // 实体类模板
.mapper("/templates/mapper.java.vm") // Mapper接口模板
.service("/templates/service.java.vm") // Service层模板
.controller("/templates/controller.java.vm")// Controller层模板
.build();
this.setTemplate(templateConfig);
}
}
```
#### 启动代码生成过程
编写一个简单的 Java 应用来启动整个代码生成功能,并传入数据库连接参数以及表名列表作为输入源。
```java
import com.baomidou.mybatisplus.generator.AutoGenerator;
import org.springframework.boot.CommandLineRunner;
public class CodeGenApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(CodeGenApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
AutoGenerator mpg = new AutoGenerator(new CustomGenerationStrategy());
mpg.execute(); // 执行代码生成操作
}
}
```
上述方法展示了如何基于官方提供的 API 来定制化 MyBatis Plus 的代码生成工具链,从而满足不同业务场景下的需求[^1]。
阅读全文
相关推荐


















