SpringBoot项目配置c3p0数据源


一、导入依赖

<dependency>
       <groupId>com.mchange</groupId>
       <artifactId>c3p0</artifactId>
       <version>0.9.5.5</version>
 </dependency>
 <dependency>
       <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.3</version>
</dependency>

二、在application.yaml配置数据源信息

 
 
spring:
datasource:
url: jdbc:mysql://localhost:3306/hrsystem?serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.mchange.v2.c3p0.ComboPooledDataSource
acquireIncrement: 11
acquireRetryAttempts: 7
 

三、创建DataSourceConfig配置dataSource

package com.zzx.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary//自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        return DataSourceBuilder.create().type(ComboPooledDataSource.class).build();
    }
}

四、启动类添加注解

@MapperScan("com.zzx.dao")//扫描mapper接口与配置文件,如果配置文件和接口不在同一个包下,要在配置文件中配置xml路径
@SpringBootApplication
public class HrsystemApplication {
    public static void main(String[] args) {
        SpringApplication.run(HrsystemApplication.class, args);
    }

}

五、添加MyBatis配置

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.zzx.dao
    #打印mybatis日志
  configuration:
    log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl

 

PS:遇到报错:java.io.FileNotFoundException: C:\Users\ABC\.m2\repository\com\mchange\c3p0\0.9.5.2\mchange-commons-java-0.2.11.jar (The system cannot find the file specified)

在C:\Users\ABC\.m2\repository\com\mchange\c3p0\0.9.5.2\放置mchange-commons-java-0.2.11.jar即可


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM