# SpringBoot中如何使用tk.mybatis代碼生成器
## 一、tk.mybatis簡介
tk.mybatis是一個基于MyBatis的輕量級通用Mapper框架,它通過提供通用Mapper接口和代碼生成器,可以大幅減少MyBatis開發中的重復代碼。其中代碼生成器模塊能夠根據數據庫表結構自動生成:
- 實體類(Entity)
- Mapper接口
- XML映射文件
## 二、環境準備
### 1. 添加依賴
在SpringBoot項目的`pom.xml`中添加以下依賴:
```xml
<!-- tk.mybatis核心包 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<!-- 代碼生成器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-generator</artifactId>
<version>1.1.5</version>
<scope>provided</scope>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
確保application.yml中已配置數據源:
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_db?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
在test目錄下新建GeneratorRunner.java:
public class GeneratorRunner {
public static void main(String[] args) {
// 代碼生成器配置
AutoGenerator generator = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
gc.setAuthor("YourName");
gc.setOpen(false);
generator.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/your_db");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
generator.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.demo");
pc.setEntity("entity");
pc.setMapper("mapper");
generator.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setInclude("user", "order"); // 需要生成的表名
generator.setStrategy(strategy);
generator.execute();
}
}
| 配置項 | 說明 |
|---|---|
| setOutputDir | 指定生成文件的輸出目錄 |
| setInclude | 指定需要生成的表(支持多表,用逗號分隔) |
| setEntityLombokModel | 是否使用Lombok注解(推薦true) |
| setNaming | 數據庫字段到實體屬性的命名策略(推薦下劃線轉駝峰) |
GeneratorRunner.main()方法生成成功提示后,檢查目標目錄:
src/main/java
└── com
└── example
└── demo
├── entity # 實體類
├── mapper # Mapper接口
└── xml # XML映射文件
@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
}
src/main/resources/generator下的.ftl文件定制生成模板通過tk.mybatis代碼生成器,我們可以在SpringBoot項目中快速生成基礎CRUD代碼,將開發效率提升50%以上。相比傳統MyBatis開發方式,減少了大量重復工作,讓開發者更專注于業務邏輯實現。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。