springboot如何自动注入sqlSessionFactory和sqlSessionTemplate
时间: 2023-11-20 11:59:48 浏览: 86
在Spring Boot中,我们可以使用@MapperScan注解来自动扫描Mapper接口并将其注入到SqlSessionTemplate中。同时,我们还需要在配置文件中配置SqlSessionFactory和SqlSessionTemplate。
以下是自动注入sqlSessionFactory和sqlSessionTemplate的步骤:
1.在pom.xml文件中添加mybatis-spring-boot-starter依赖:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
```
2.在配置文件中配置数据源和MyBatis:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
```
3.在启动类上添加@MapperScan注解:
```java
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
4.在Mapper接口中使用@Mapper注解:
```java
@Mapper
public interface UserMapper {
// ...
}
```