错误:无法创建PoolableConnectionFactory(isValid()返回false)

时间:2017-04-20 14:01:44

标签: java hibernate junit

有什么问题?我使用H2 DATABASE

有人能解决我的问题吗? 我使用H2 DATA BASE,Hibernate 5

这个hy HibernateConfig.java

package com.train.shoponlinebackend.config;
@Configuration
@ComponentScan(basePackages = {"com.train.shoponlinebackend.dto"})
@EnableTransactionManagement
public class HibernateConfig {

private static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping";
private static String DATABASE_DRIVER = "org.h2.Driver";
private static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
private static String DATABASE_USERNAME = "sa";
private static String DATABASE_PASSWORD = "";
@Bean
public DataSource getDataSource() {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(DATABASE_DRIVER);
    dataSource.setUrl(DATABASE_URL);
    dataSource.setUsername(DATABASE_USERNAME);
    dataSource.setPassword(DATABASE_PASSWORD);

    return dataSource;
}

@Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);

    builder.addProperties(getHibernateProperties());
    builder.scanPackages("com.train.shoponlinebackend.dto");

    return builder.buildSessionFactory();
}

private Properties getHibernateProperties() {
    // TODO Auto-generated method stub
    Properties properties = new Properties();
    properties.put("hibernate.dialect", DATABASE_DIALECT);
    properties.put("hibernate.show_sql", true);
    properties.put("hibernate.format_sql", true);

    return properties;
}

@Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);

    return transactionManager;
}

}

我在DAO IMPL中的方法:

@Repository("categoryDAO")
public class CategoryDAOImpl implements CategoryDAO {

    @Autowired
    private SessionFactory sessionFactory;


    @Override
        @Transactional
        public boolean add(Category category) {
            try {
                // add category
                sessionFactory.getCurrentSession().persist(category);
                return true;

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
}

我的JUNIT测试

@Test
    public void testAdCategory(){
        category = new Category();
        category.setActive(true);
        category.setDescription("This is some description of TV");
        category.setImageURL("CAT_1.png");
        category.setName("Television");

        assertEquals("Success added category", true, categoryDAO.add(category));
    }

运行junit测试时出现错误:

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy28.add(Unknown Source)
    at com.train.shoponlinebackend.test.CategoryTestCase.testAdCategory(CategoryTestCase.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
    at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:514)
    at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:448)
    ... 32 more
Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory (isValid() returned false)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2294)
    at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039)
    at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
    at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
    ... 35 more
Caused by: java.sql.SQLException: isValid() returned false
    at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:284)
    at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357)
    at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2307)
    at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2290)
    ... 40 more

2 个答案:

答案 0 :(得分:2)

检查pom.xml文件中的h2版本。

如果h2数据库引擎是1.4.194,那么通过maven或gradle为h2数据库驱动程序添加的依赖关系也应该是1.4.194。

答案 1 :(得分:0)

我将重述根本原因(和解决方案),因为每次要使用H2时都会遇到此问题。事业是如此简单和明显......

安装H2并获得有效连接后,请检查您安装的H2 bin Jar(主类)的精确版本(再次 - 在H2服务器位置而不是您的程序)。这是我正在使用的(本月..):

C:\Program Files (x86)\H2\bin\h2-1.4.195.jar 

当然你的H2服务器可能在另一个平台或位置..

规则:当您设置类路径(即项目的maven POM文件)时**始终在程序中指定与H2服务器使用的完全相同的H2 jar文件**(即上面的那个)为了我)。 H2非常挑剔。

maven用户可能在其POM文件中指定了此内容:

<!-- H2 DATABASE -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.193</version> <!-- Does not match the server jar -->
</dependency>

参见&#34; 193&#34;?这与上面的服务器(见上面的jar)不同(使用195)。

更改pom以使用195将解决问题(替换您在此处使用的任何H2版本)

    <!-- H2 DATABASE -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.195</version> <!-- Matches the server JAR -->
    </dependency>

如果您感到沮丧或无法访问maven存储库,只需将上面安装的H2服务器jar文件(项目外部)复制到项目中(maven之外)并继续...