Spring Boot 3 集成 MyBatis 连接 MySQL 数据库
Spring Boot 3 集成 MyBatis 连接 MySQL 数据库的步骤:
以下是集成 Spring Boot 3、MyBatis、HikariCP 连接池并操作 MySQL 数据库的完整步骤和代码:
一、创建 Spring Boot 项目
添加以下依赖:
<dependencies><!-- Spring 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.4</version></dependency><!-- MySQL 驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- HikariCP 连接池 (默认集成,无需显式添加) --><!-- Lombok (可选) --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
</dependencies>
二、配置数据库连接
在 src/main/resources/application.yml
中添加配置:
spring:datasource:url: jdbc:mysql://localhost:3306/his2?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=trueusername: rootpassword: yourpassworddriver-class-name: com.mysql.cj.jdbc.Driverhikari:maximum-pool-size: 10 # 最大连接数minimum-idle: 5 # 最小空闲连接idle-timeout: 30000 # 空闲连接超时时间(毫秒)connection-timeout: 30000 # 连接超时时间(毫秒)max-lifetime: 1800000 # 连接最大生命周期(毫秒)mybatis:mapper-locations: classpath:mapper/*.xml # Mapper XML 文件位置type-aliases-package: com.example.entity # 实体类包路径configuration:map-underscore-to-camel-case: true # 开启驼峰命名映射cache-enabled: true # 开启二级缓存
三、创建实体类
src/main/java/com/example/entity/User.java
:
import lombok.Data;@Data
public class User {private Long id;private String username;private String password;private Integer age;private String email;private LocalDateTime createTime;
}
四、创建 Mapper 接口
src/main/java/com/example/mapper/UserMapper.java
:
import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface UserMapper {// 查询所有用户List<User> selectAll();// 根据 ID 查询用户User selectById(Long id);// 插入用户int insert(User user);// 更新用户int update(User user);// 删除用户int deleteById(Long id);
}
五、创建 Mapper XML 文件
src/main/resources/mapper/UserMapper.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><resultMap id="BaseResultMap" type="User"><id column="id" property="id" /><result column="username" property="username" /><result column="password" property="password" /><result column="age" property="age" /><result column="email" property="email" /><result column="create_time" property="createTime" /></resultMap><select id="selectAll" resultMap="BaseResultMap">SELECT * FROM user</select><select id="selectById" resultMap="BaseResultMap">SELECT * FROM user WHERE id = #{id}</select><insert id="insert" parameterType="User">INSERT INTO user (username, password, age, email, create_time)VALUES (#{username}, #{password}, #{age}, #{email}, #{createTime})</insert><update id="update" parameterType="User">UPDATE userSET username = #{username},password = #{password},age = #{age},email = #{email}WHERE id = #{id}</update><delete id="deleteById" parameterType="Long">DELETE FROM user WHERE id = #{id}</delete>
</mapper>
六、创建 Service 层
src/main/java/com/example/service/UserService.java
:
import com.example.entity.User;import java.util.List;public interface UserService {List<User> getAllUsers();User getUserById(Long id);int saveUser(User user);int updateUser(User user);int deleteUser(Long id);
}
src/main/java/com/example/service/impl/UserServiceImpl.java
:
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service
@Transactional
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> getAllUsers() {return userMapper.selectAll();}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Overridepublic int saveUser(User user) {return userMapper.insert(user);}@Overridepublic int updateUser(User user) {return userMapper.update(user);}@Overridepublic int deleteUser(Long id) {return userMapper.deleteById(id);}
}
七、创建 Controller 层
src/main/java/com/example/controller/UserController.java
:
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;// 获取所有用户@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}// 根据 ID 获取用户@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}// 添加用户@PostMappingpublic int saveUser(@RequestBody User user) {return userService.saveUser(user);}// 更新用户@PutMapping("/{id}")public int updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);return userService.updateUser(user);}// 删除用户@DeleteMapping("/{id}")public int deleteUser(@PathVariable Long id) {return userService.deleteUser(id);}
}
八、启用 MyBatis
在主应用类上添加 @MapperScan
注解:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
九、数据库表结构
确保 MySQL 数据库 his2
中存在 user
表:
CREATE DATABASE his2;USE his2;CREATE TABLE user (id BIGINT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL,password VARCHAR(100) NOT NULL,age INT,email VARCHAR(50),create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
十、测试应用
启动应用后,使用工具(如 Postman)测试接口:
-
获取所有用户
GET http://localhost:8080/api/users
-
获取单个用户
GET http://localhost:8080/api/users/1
-
添加用户
POST http://localhost:8080/api/users 请求体: {"username": "test","password": "123456","age": 25,"email": "test@example.com" }
-
更新用户
PUT http://localhost:8080/api/users/1 请求体: {"username": "updated","age": 26 }
-
删除用户
DELETE http://localhost:8080/api/users/1
十一、连接池配置
Spring Boot 3 默认使用 HikariCP 连接池,通过 spring.datasource.hikari
配置:
maximum-pool-size
: 最大连接数(默认 10)minimum-idle
: 最小空闲连接数(默认与 maximum-pool-size 相同)idle-timeout
: 空闲连接超时时间(默认 30000 毫秒)connection-timeout
: 获取连接超时时间(默认 30000 毫秒)max-lifetime
: 连接最大生命周期(默认 1800000 毫秒)
十二、同包存放
- 同包存放:Mapper 接口和 XML 文件放在同一包下时,无需额外配置
mapper-locations
,MyBatis 会自动识别。 - 核心配置:确保
@MapperScan
扫描到 Mapper 包,并通过application.yml
配置数据库连接和连接池参数。 - 资源打包:若 XML 在 Java 源码目录下,需在
pom.xml
中配置资源过滤,确保其被编译到类路径中。 -
问题 1:XML 文件未被打包到类路径中
如果 XML 文件未被编译到
target/classes
目录下,需在pom.xml
中配置资源过滤:<build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include> <!-- 包含 Java 目录下的 XML 文件 --></includes></resource><resource><directory>src/main/resources</directory></resource></resources> </build>
问题 2:手动指定 XML 路径(非必须)
如果 XML 与 Mapper 接口不在同一包,需在
application.yml
中明确指定 XML 位置:mybatis:mapper-locations: classpath:/mapper/**/*.xml # 例如:XML 放在 resources/mapper 目录下
十三、关于传统的MyBatis 中的
SqlMapConfig.xml
-
- 传统 Spring + MyBatis:需要
SqlMapConfig.xml
配置 MyBatis 基础信息,再由 Spring 加载。 - Spring Boot + MyBatis:无需
SqlMapConfig.xml
,通过自动配置和属性文件即可完成大部分配置,更简洁。 - 什么时候需要自定义配置?
当需要修改 MyBatis 全局行为(如添加插件、自定义类型处理器)时,可通过 Java 配置类(@Configuration
+@Bean
)替代传统的 XML 配置,例如:java
@Configuration public class MyBatisConfig {@Beanpublic MyBatisConfiguration myBatisConfiguration() {MyBatisConfiguration configuration = new MyBatisConfiguration();configuration.setMapUnderscoreToCamelCase(true); // 开启驼峰映射return configuration;} }
- 传统 Spring + MyBatis:需要