mybatisplus如何指定使用druid数据源
时间: 2023-06-29 19:02:22 浏览: 54
在 MybatisPlus 中,指定使用 Druid 数据源需要以下几个步骤:
1. 在 pom.xml 中添加 druid 和 mybatis-plus-boot-starter 依赖:
```
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
```
2. 在 application.yml 配置文件中添加 Druid 数据源的配置:
```
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
filters: stat,wall
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
```
3. 在 MybatisPlus 的配置文件中指定使用 Druid 数据源:
```
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public DruidDataSource dataSource() {
return new DruidDataSource();
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
return new MybatisPlusInterceptor();
}
@Bean
public MybatisSqlSessionFactoryBean sqlSessionFactory(DruidDataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
//其他配置
return sqlSessionFactoryBean;
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
```
在上述代码中,`dataSource()` 方法返回 Druid 数据源对象,`sqlSessionFactory()` 方法中将 Druid 数据源对象传入 MybatisSqlSessionFactoryBean 中,以便 MybatisPlus 使用该数据源。