springboot集成mybatis的过程
时间: 2024-09-13 18:18:20 浏览: 37
Spring Boot 集成 MyBatis 主要有以下几个步骤:
1. **添加依赖**:首先,在你的`pom.xml`文件中引入Spring Data JPA、Spring JDBC以及MyBatis的依赖。例如:
```xml
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- 如果需要支持JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
```
2. **配置数据源**:如果你已经有一个数据库配置,可以在`application.properties`或`application.yml`里设置数据源的信息。比如:
```
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=your_password
```
3. **创建Mapper接口**:定义你的业务逻辑映射到SQL的方法,比如:
```java
public interface UserMapper {
User selectUserById(int id);
}
```
4. **配置SqlSessionFactory**:在Spring Boot的配置类上应用`@EnableAutoConfiguration`注解,并启用MyBatis自动配置:
```java
@Configuration
@EnableAutoConfiguration
public class AppConfig {
@Bean
public SqlSessionFactory sqlSessionFactory(MyBatisConfig myBatisConfig) throws Exception {
return new SqlSessionFactoryBuilder().build(myBatisConfig.getConfiguration());
}
// 其他配置...
}
```
通常会注入`DataSource`并构建`SqlSessionFactoryBean`。
5. **扫描Mapper接口**:在`AppConfig`或单独的模块配置类中,指定Mapper接口所在的包名,让Spring Boot去扫描它们,如:
```java
@ComponentScan("com.example.demo.mapper")
```
6. **注入Mapper**:现在你可以在Service层注入Mapper接口,然后调用方法:
```java
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
```
阅读全文