本文将手把手带你完成 Spring Boot 与 MyBatis 的整合,从环境搭建到完整的增删改查(CRUD)功能实现,并穿插展示如何在 TRAE IDE 中高效完成整个开发流程。
01|环境准备与项目初始化
1.1 开发环境要求
- JDK:8 及以上(推荐 11)
- Maven:3.6+
- MySQL:5.7+ 或 8.0+
- TRAE IDE:最新版(内置 Spring Initializr,一键生成骨架代码)
1.2 使用 TRAE IDE 快速创建项目
打开 TRAE IDE,按下 Ctrl+Shift+P → 输入 Spring Initializr → 选择:
| 选项 | 值 |
|---|---|
| Group | com.example |
| Artifact | demo-mybatis |
| Dependencies | Spring Web、MyBatis Framework、MySQL Driver、Lombok |
TRAE 会自动生成目录结构,并智能识别 pom.xml 中缺失的依赖,侧边对话 会提示:
“检测到 MyBatis,是否添加 pagehelper 分页插件?”—— 点“是”即可。
02|依赖与数据源配置
2.1 完整 pom.xml 依赖
<!-- 父坐标 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
</parent>
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 分页插件(可选) -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>2.2 application.yml 数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo_mybatis?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# MyBatis 配置
mybatis:
configuration:
map-underscore-to-camel-case: true # 下划线转驼峰
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台打印 SQL
mapper-locations: classpath:mapper/*.xml # XML 映射文件位置
type-aliases-package: com.example.demomybatis.entity # 别名包
# 分页插件
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true在 TRAE IDE 中,行内对话 选中
password: 123456→ 输入“加密” → 自动弹出 Jasypt 加密提示,一键替换为ENC(xxx)