如何使用连接池在Spring启动时使用hibernate(c3p0)?

时间:2017-11-04 06:03:18

标签: mysql hibernate spring-boot connection-pooling c3p0

我是Spring Boot应用程序的新手。我想在 Spring Boot Application 中使用连接池 Hibernate ,但我无法实现连接池。我在 Spring Boot Application 上添加了以下配置。

Gradle依赖关系如下:

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-data-jpa")
runtime('org.springframework.boot:spring-boot-devtools')
runtime('mysql:mysql-connector-java')
compile("com.mchange:c3p0:0.9.5.2")
testCompile('org.springframework.boot:spring-boot-starter-test')}

Spring Boot配置如下:

@Configuration
@EnableTransactionManagement
public class WebConfig{

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/testDb");
    dataSource.setUsername("test");
    dataSource.setPassword("test");
    return dataSource;
}

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource());
    sessionFactoryBean.setPackagesToScan("com.java.test");
    sessionFactoryBean.setHibernateProperties(hibProperties());
    return sessionFactoryBean;
}

private Properties hibProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect","org.hibernate.dialect.MySQL5InnoDBDialect");
    properties.put("hibernate.show_sql","true");
    properties.put("hibernate.current_session_context_class","org.springframework.orm.hibernate5.SpringSessionContext");        
    properties.put("connection.provider_class","org.hibernate.connection.C3P0ConnectionProvider");
    properties.put("hibernate.c3p0.min_size","10");
    properties.put("hibernate.c3p0.max_size",50);
    properties.put("hibernate.c3p0.acquire_increment","5");
    properties.put("hibernate.c3p0.idle_test_period","600");
    properties.put("hibernate.c3p0.timeout","5000");
    return properties;
}

@Bean
public HibernateTransactionManager transactionManager(){
    HibernateTransactionManager transactionManager = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory().getObject());
    return transactionManager;
}
}

当我在MySQL Workbanch上运行以下命令时:

show processlist;

我的输出如下:

Id  User    Host    db  Command Time    State   Info
454 test    localhost:58383     Sleep   141     
455 test    localhost:58384     Query   0   starting    show processlist

我只是想用 hibernate 弹簧启动应用程序> 实现连接池 错误 强>

1 个答案:

答案 0 :(得分:0)

c3p0需要数据类型为ComboPooledDataSource

尝试从

更改数据源配置
@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    ...
}

@Bean
public DataSource dataSource(){
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    ...
}