# MyBatis-Plus如何配置環境
MyBatis-Plus(簡稱MP)是MyBatis的增強工具,在保留原生功能的基礎上提供了更多便捷功能。本文將詳細介紹如何從零開始配置MyBatis-Plus環境。
## 一、環境準備
### 1. 基礎依賴
確保項目中已包含:
- JDK 1.8+
- Maven 3.0+
- Spring Boot 2.x(可選)
- MyBatis 3.5+
### 2. 開發工具推薦
- IDEA/Eclipse
- MySQL 5.7+
- Postman(API測試)
## 二、Maven項目配置
### 1. 添加核心依賴
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mp_demo?useSSL=false
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 開啟SQL日志
global-config:
db-config:
id-type: auto # 主鍵自增策略
@SpringBootApplication
@MapperScan("com.example.mapper") // 掃描Mapper接口
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mp_demo", "root", "123456")
.globalConfig(builder -> builder.outputDir("src/main/java"))
.packageConfig(builder -> builder.parent("com.example"))
.strategyConfig(builder -> builder.addInclude("user"))
.execute();
spring.datasource
配置@TableName
注解指定表名@TableId
標注主鍵@TableField
檢查是否配置了日志實現:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
建議使用第三方組件:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.6.1</version>
</dependency>
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor interceptor = new PerformanceInterceptor();
interceptor.setFormat(true); // 格式化SQL
return interceptor;
}
通過以上步驟即可完成MyBatis-Plus的基礎環境配置。更多高級功能可參考官方文檔。 “`
該文檔包含: 1. 環境要求說明 2. 分步驟的配置指南 3. 代碼示例和YAML配置 4. 常見問題解決方案 5. 擴展功能建議 6. 官方文檔引用
可根據實際項目需求調整數據庫配置、包路徑等參數。建議在正式項目中使用更高版本的依賴。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。