在Hibernate中空闲5分钟后无法连接到db

时间:2017-03-21 23:29:49

标签: mysql spring hibernate jpa c3p0

我在我的spring应用程序中使用Hibernate连接到msql db。

启动时工作正常,但在闲置约5分钟后我一直收到跟踪错误。

org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.

不确定出了什么问题。 以下是我用于连接的代码

@Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean userMasterEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        em.setPackagesToScan(new String[] { "com.test.master" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("hibernate.id.new_generator_mappings", "false");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

        properties.put("hibernate.c3p0.min_size", "5");
        properties.put("hibernate.c3p0.max_size", "20");
        properties.put("hibernate.c3p0.timeout", "300");
        properties.put("hibernate.c3p0.max_statements", "50");
        properties.put("hibernate.c3p0.idle_test_period", "3000");
        properties.put("hibernate.default_schema", "gmt_master");

        em.setJpaPropertyMap(properties);
        return em;
    }

请告诉我如何解决此问题,

先谢谢。

1 个答案:

答案 0 :(得分:0)

您应该将hibernate.c3p0.idle_test_period更改为小于hibernate.c3p0.timeout,例如

properties.put("hibernate.c3p0.idle_test_period", "100");

您希望在池中因空闲而关闭之前验证池中的空闲连接。