spring Boot 集成 MyBatis 教程
本文将基于 Spring Boot 3.x 和 MyBatis 3.5+,结合最新实践,分步骤详解如何高效集成 MyBatis,并解决常见配置问题。
一、环境准备与依赖配置
-
创建 Spring Boot 项目
使用 Spring Initializr生成基础项目,选择以下依赖:
-
Spring Web
-
MySQL Driver
-
Lombok(可选)
-
-
添加核心依赖
在
pom.xml中添加 MyBatis Spring Boot Starter:<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
二、配置数据源与 MyBatis
-
配置
application.ymlspring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml # XML 映射文件路径 type-aliases-package: com.example.entity # 实体类包路径 configuration: map-underscore-to-camel-case: true # 开启驼峰命名转换 cache-enabled: false # 关闭二级缓存(生产环境按需开启) -
可选:Java 配置类
若需复杂配置(如动态数据源),可创建配置类:
@Configuration @MapperSc

最低0.47元/天 解锁文章
771

被折叠的 条评论
为什么被折叠?



