一、项目初始化与基础配置
1.1 创建Spring Boot 3项目
通过主流IDE(如IntelliJ IDEA或Eclipse)的Spring Initializr插件快速生成项目骨架,需注意以下关键配置:
- 基础依赖:选择Spring Web、MyBatis Framework、MySQL Driver等核心组件
- JDK版本:确保使用JDK 17或更高版本(Spring Boot 3最低要求)
- 构建工具:推荐使用Maven进行依赖管理,项目结构需符合Maven标准目录规范
1.2 配置文件优化
将默认的application.properties转换为YAML格式的application.yml,实现更清晰的层级配置:
server:port: 8080spring:datasource:url: jdbc:mysql://localhost:3306/demo_dbusername: rootpassword: '012345' # 密码以0开头需加引号driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.demo.entity
关键说明:
- 数据库密码若以数字0开头,必须使用单引号包裹避免自动截断
- 通过
mapper-locations指定MyBatis映射文件存放路径 - 使用
type-aliases-package简化实体类全限定名引用
1.3 依赖管理优化
在pom.xml中添加必要依赖时,建议使用版本管理属性避免硬编码:
<properties><java.version>17</java.version><mybatis-spring-boot.version>3.0.3</mybatis-spring-boot.version></properties><dependencies><!-- Spring Boot Starter --><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>${mybatis-spring-boot.version}</version></dependency><!-- MySQL驱动 --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope></dependency></dependencies>
二、数据库集成方案
2.1 数据库表设计
以用户管理模块为例,创建基础表结构:
CREATE TABLE `user` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',`username` varchar(50) NOT NULL COMMENT '用户名',`email` varchar(100) DEFAULT NULL COMMENT '电子邮箱',`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',PRIMARY KEY (`id`),UNIQUE KEY `idx_username` (`username`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户信息表';
2.2 实体类开发
遵循JavaBean规范创建实体类,推荐使用Lombok简化代码:
@Data@NoArgsConstructor@AllArgsConstructor@TableName("user") // 若使用通用Mapper可添加此注解public class User {@TableId(type = IdType.AUTO) // 主键自增策略private Long id;@NotBlank(message = "用户名不能为空")private String username;@Email(message = "邮箱格式不正确")private String email;private LocalDateTime createTime;private LocalDateTime updateTime;}
2.3 MyBatis映射配置
采用XML映射文件方式实现SQL管理:
<!-- UserMapper.xml --><mapper namespace="com.example.demo.mapper.UserMapper"><resultMap id="BaseResultMap" type="User"><id column="id" property="id"/><result column="username" property="username"/><result column="email" property="email"/><result column="create_time" property="createTime"/><result column="update_time" property="updateTime"/></resultMap><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO user(username, email)VALUES(#{username}, #{email})</insert><select id="selectById" resultMap="BaseResultMap">SELECT * FROM user WHERE id = #{id}</select></mapper>
三、业务逻辑实现
3.1 Mapper接口定义
创建标准CRUD接口,推荐使用MyBatis-Plus的IService接口扩展:
public interface UserMapper extends BaseMapper<User> {// 自定义复杂查询方法List<User> selectByCondition(@Param("condition") Map<String, Object> condition);}
3.2 Service层实现
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User createUser(UserDTO userDTO) {User user = new User();BeanUtils.copyProperties(userDTO, user);userMapper.insert(user);return user;}@Overridepublic User getUserById(Long id) {return userMapper.selectById(id);}@Override@Transactionalpublic boolean updateUser(UserDTO userDTO) {User user = userMapper.selectById(userDTO.getId());if (user == null) {throw new RuntimeException("用户不存在");}BeanUtils.copyProperties(userDTO, user);return userMapper.updateById(user) > 0;}}
3.3 Controller层开发
@RestController@RequestMapping("/api/users")public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) {User user = userService.createUser(userDTO);return ResponseEntity.created(URI.create("/api/users/" + user.getId())).body(user);}@GetMapping("/{id}")public ResponseEntity<User> getUser(@PathVariable Long id) {return ResponseEntity.ok(userService.getUserById(id));}@PutMapping("/{id}")public ResponseEntity<Void> updateUser(@PathVariable Long id,@Valid @RequestBody UserDTO userDTO) {userDTO.setId(id);if (userService.updateUser(userDTO)) {return ResponseEntity.ok().build();}return ResponseEntity.notFound().build();}}
四、高级配置与优化
4.1 分页插件配置
添加PageHelper分页支持:
@Configurationpublic class MyBatisConfig {@Beanpublic PageInterceptor pageInterceptor() {PageInterceptor interceptor = new PageInterceptor();Properties properties = new Properties();properties.setProperty("reasonable", "true");properties.setProperty("supportMethodsArguments", "true");interceptor.setProperties(properties);return interceptor;}}
4.2 动态数据源配置
针对多数据源场景,可实现AbstractRoutingDataSource:
public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.getDataSourceType();}}// 配置类示例@Configurationpublic class DataSourceConfig {@Bean@ConfigurationProperties("spring.datasource.master")public DataSource masterDataSource() {return DataSourceBuilder.create().build();}@Beanpublic DataSource dynamicDataSource() {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("master", masterDataSource());// 添加其他数据源...DynamicDataSource dynamicDataSource = new DynamicDataSource();dynamicDataSource.setTargetDataSources(targetDataSources);dynamicDataSource.setDefaultTargetDataSource(masterDataSource());return dynamicDataSource;}}
4.3 性能监控方案
集成Actuator实现MyBatis监控:
management:endpoints:web:exposure:include: metrics,health,infoendpoint:metrics:enabled: true
五、常见问题解决方案
5.1 启动报错处理
- 包扫描失败:检查
@MapperScan注解配置是否正确 - 数据库连接失败:验证数据库服务状态及网络连通性
- SQL语法错误:检查MySQL版本与驱动兼容性
5.2 事务失效场景
- 确保事务方法为public修饰
- 检查是否在同一个类中调用事务方法
- 验证是否正确引入
@Transactional注解
5.3 分页参数失效
- 检查PageHelper.startPage()调用位置
- 验证拦截器配置顺序是否正确
- 确保SQL语句后直接获取结果集
本文通过完整的项目实践,系统阐述了Spring Boot 3与MyBatis整合开发的核心要点。从基础配置到高级特性,每个环节都提供了可落地的解决方案和最佳实践建议。开发者可基于此框架快速构建企业级应用,同时可根据实际需求灵活扩展功能模块。建议在实际开发过程中结合日志系统、单元测试等工程化实践,构建更健壮的应用体系。