在Spring Boot中整合MyBatis涉及到几个关键步骤,包括添加依赖、配置数据源、配置MyBatis、创建实体类、编写Mapper接口和XML映射文件,以及在服务层使用这些组件。
步骤1:添加依赖
在pom.xml
中添加MyBatis和MyBatis-Spring-Boot-Starter的依赖。MyBatis-Spring-Boot-Starter包含了MyBatis和Spring Boot的整合所需的所有依赖。
<dependencies>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version> <!-- 根据实际情况选择合适的版本 -->
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot JPA依赖,如果不需要可以移除 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>provided</scope>
</dependency>
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>