Spring Boot 集成 MyBatis 主要包括以下几个步骤:
- 添加依赖:在你的
pom.xml
文件中添加 Spring Boot 和 MyBatis 的起步依赖(starter dependency)。<!-- Spring Boot起步依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis起步依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>你的版本号</version> </dependency> <!-- 数据库驱动依赖,以MySQL为例 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>你的版本号</version> </dependency>
- 配置数据源:在
application.properties
或application.yml
文件中配置数据库连接信息。# application.properties spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 配置MyBatis:在配置文件中配置 MyBatis 相关设置,例如类型别名、映射器等。
# application.properties mybatis.type-aliases-package=你的实体类所在包 mybatis.mapper-locations=classpath:mapper/*.xml
- 创建实体类:根据你的数据库表创建对应的实体类(Entity)。
- 创建映射文件:创建 MyBatis 的映射文件(XML Mapper),定义 SQL 语句和映射规则。
<!-- 在 resources/mapper/YourEntityMapper.xml --> <mapper namespace="你的Mapper接口路径"> <select id="selectById" resultType="你的实体类路径"> SELECT * FROM your_table WHERE id = #{id} </select> </mapper>
- 创建Mapper接口:定义一个接口用于操作数据库,并使用
@Mapper
注解或在启动类上使用@MapperScan
指定扫描的Mapper接口路径。// @Mapper 或者在启动类上使用 @MapperScan public interface YourEntityMapper { YourEntity selectById(int id); }
- 启动类配置:确保你的 Spring Boot 启动类上添加了
@SpringBootApplication
注解,并在适当的地方使用@MapperScan
注解。@SpringBootApplication @MapperScan("你的Mapper接口所在包") public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }
- 编写服务层和控制器:创建服务层(Service)调用 Mapper 接口中的方法,并在控制器(Controller)中调用服务层逻辑。
- 测试:编写测试用例,确保集成无误。
按照以上步骤操作后,你的 Spring Boot 应用应该能够成功集成 MyBatis,并且可以通过 MyBatis 的 Mapper 接口操作数据库。记得根据实际情况调整依赖版本和配置细节。