Tomcat找不到H2内存数据库

时间:2016-02-25 18:22:49

标签: java hibernate maven tomcat h2

出于测试目的,我正在尝试将hibernate与h2内存数据库一起使用。我正在使用Maven进行依赖管理。 Tomcat似乎没有找到h2数据库驱动程序 - 但是,通过maven添加postgresql,启动本地postgresql-daemon并连接到它就可以了。

我还能够针对h2内存数据库运行一些简单的JUnit-Tests(没有tomcat)。

我的初始化代码(用代码而不是xml来排除那里的任何错误):

Properties props = new Properties();

// h2 in-memory
props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
props.setProperty("hibernate.connection.url", "jdbc:h2:mem:test");

// postgresql
props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
props.setProperty("hibernate.connection.username", "admin");
props.setProperty("hibernate.connection.password", "...password...");
props.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost:5432/glmtest");

// Common Options
props.setProperty("hibernate.connection_pool_size", "1");
props.setProperty("hibernate.hbm2ddl.auto", "create");
props.setProperty("hibernate.show_sql", "true");

sessionFactory =  
        new Configuration()
        .addProperties(props)
        .addAnnotatedClass( AnEntity.class )
        .buildSessionFactory();

如果我使用H2初始化对这个类运行单元测试,一切正常。在tomcat上部署时,会显示以下错误:

org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
[...]

org.hibernate.exception.JDBCConnectionException: Error calling DriverManager#getConnection
org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:101)
org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:123)
[...]

java.sql.SQLException: No suitable driver found for jdbc:h2:mem:test
java.sql.DriverManager.getConnection(DriverManager.java:689)
java.sql.DriverManager.getConnection(DriverManager.java:208)
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionCreator.makeConnection(DriverManagerConnectionCreator.java:34)
[...]

this page上显示完整错误。

两个库(h2和psql)都是通过Maven安装的,两者都没有作用域(默认为“compile”)。我在正确的tomcat服务器上,我正在正确部署(因为postgresql确实有效),tomcat和java正在使用相同的JRE8运行时环境。其他已注册的Web服务(主项目使用JAX)没有按预期的数据库依赖性工作。

我没有想法 - 任何帮助都非常感激。

1 个答案:

答案 0 :(得分:3)

您正在为posgresql设置Driver类,但不为h2

设置
props.setProperty("hibernate.connection.driver_class", "org.h2.Driver");