Spring Boot 2.x 基础教程:使用 MyBatis 访问 MySQL
在 Spring Boot 中整合 MyBatis 完成关系型数据库的增删改查操作。
整合 MyBatis
第一步:新建 Spring Boot 项目,在 pom.xml 中引入 MyBatis 的 Starter 以及 MySQL Connector 依赖,具体如下:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
关于 mybatis-spring-boot-starter 的版本需要注意:
2.1.x版本适用于:MyBatis 3.5+、Java 8+、Spring Boot 2.1+2.0.x版本适用于:MyBatis 3.5+、Java 8+、Spring Boot 2.0/2.11.3.x版本适用于:MyBatis 3.4+、Java 6+、Spring Boot 1.5
其中,目前还在维护的是 2.1.x 版本和 1.3.x 版本。
第二步:同之前介绍的使用 jdbc 模块和 jpa 模块连接数据库一样,在 application.properties 中配置 mysql 的连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
第三步:Mysql 中创建一张用来测试的表,比如:User 表,其中包含 id(BIGINT)、age(INT)、name(VARCHAR) 字段。
具体创建命令如下:
CREATE TABLE `User` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
`age` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
第四步:创建 User 表的映射对象 User:


