configurationHibernate通过JNDI数据源连接到数据库
大家好我使用Hibernate + Struts2 + Tomcat6 + Mysql作为我的J2EE框架。 我一直在使用hibernate的内置连接池机制,但事实certificate,在8小时之后,mysqlclosures它的连接时,会出现问题。 无论如何,我search了一下,发现我应该通过JNDI数据源获得我的连接,但我无法达成一个好的和完整的教程。 我应该采取什么措施来做到这一点? 请给我足够的细节,我有点新。 这里是我的hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost/hposg?characterEncoding=UTF-8 </property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">thread</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="hbm2ddl.auto">update</property> <property name="hibernate.max_fetch_depth">3</property> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.idle_test_period">300</property> <property name="hibernate.c3p0.timeout">1800</property> <property name="hibernate.c3p0.max_size">25</property> <property name="hibernate.c3p0.min_size" >3</property> <property name="hibernate.c3p0.max_statement">0</property> <property name="hibernate.c3p0.preferredTestQuery">select 1;</property> <property name="hibernate.c3p0.testConnectionOnCheckout">true</property> <property name="hibernate.c3p0.validate">true</property> <!-- Mapping files --> <mapping resource="com/hposg/hibernate/resources/Player.hbm.xml"/> <mapping resource="com/hposg/hibernate/resources/Game.hbm.xml"/> ... </session-factory> </hibernate-configuration>
我也试过这个,但没有成功:在WebContent / META-INF中创build一个context.xml包含:
<Context path="" docBase="../RSGames" debug="0" reloadable="true"> <Resource name="jdbc/RSGames" auth="Container" type="javax.sql.DataSource" username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/hposg?autoReconnect=true&useUnicode=true&characterEncoding=utf8" maxActive="15" maxIdle="7" validationQuery="Select 1" /> </Context>
把这个放在web.xml中:
<resource-ref> <description>Connection Pool</description> <res-ref-name>jdbc/RSGames</res-ref-name> <res-type>javax.sql.Datasource</res-type> <res-auth>Container</res-auth> </resource-ref>
并像这样修改hibernateconfiguration:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> ... <property name="connection.datasource">java:comp/env/jdbc/RSGames</property> ... </session-factory> </hibernate-configuration>
正如我之前提到的那样,它不会以这种方式连接到数据库。 有任何想法吗?
[编辑]当我执行应用程序,我得到这个exception:
Mar 16, 2011 12:29:13 AM com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run WARNING: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1f18cbe -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source) at java.sql.DriverManager.getDriver(Unknown Source) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:224) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:120) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:143) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:132) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) Mar 16, 2011 12:29:13 AM com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run WARNING: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@14f1726 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source) at java.sql.DriverManager.getDriver(Unknown Source) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:224) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:120) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:143) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:132) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) Mar 16, 2011 12:29:13 AM com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run WARNING: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@cad437 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.lang.NullPointerException at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source) at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source) at java.sql.DriverManager.getDriver(Unknown Source) at com.mchange.v2.c3p0.DriverManagerDataSource.driver(DriverManagerDataSource.java:224) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:120) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:143) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:132) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 29994 [http-8081-3] WARN org.hibernate.cfg.SettingsFactory - Could not obtain connection to query metadata java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:78) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:114) at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383) at com.hposg.hibernate.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:12) at com.hposg.hibernate.util.HibernateUtil.<clinit>(HibernateUtil.java:7) at com.hposg.login.LoginFactory.doLogin(LoginFactory.java:25) at com.hposg.controller.struts.LoginAction.execute(LoginAction.java:59) 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 com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 74 more
显然,你做对了。 但是,这里列出了一些你需要的东西,并用一个正在运行的应用程序的例子:
1)META-INF中的context.xml文件,指定您的数据源:
<Context> <Resource name="jdbc/DsWebAppDB" auth="Container" type="javax.sql.DataSource" username="sa" password="" driverClassName="org.h2.Driver" url="jdbc:h2:mem:target/test/db/h2/hibernate" maxActive="8" maxIdle="4"/> </Context>
2)web.xml告诉容器你正在使用这个资源:
<resource-env-ref> <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name> <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type> </resource-env-ref>
3)消耗数据源的Hibernateconfiguration。 在这种情况下,它是一个persistence.xml
,但在hibernate.cfg.xml
类似
<persistence-unit name="dswebapp"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" /> <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/> </properties> </persistence-unit>
Tomcat-7 JNDIconfiguration:
脚步:
- 打开tomcat-dir / conf中的server.xml
- 在
<GlobalNamingResources>
添加以下<Resource>
标签,其中包含您的数据库详细信息
<Resource name="jdbc/mydb" global="jdbc/mydb" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test" username="root" password="" maxActive="10" maxIdle="10" minIdle="5" maxWait="10000"/>
- 保存server.xml文件
- 在tomcat-dir / conf中打开context.xml
- 在
<Context>
标签内添加下面的<ResourceLink>
。
<ResourceLink name="jdbc/mydb" global="jdbc/mydb" auth="Container" type="javax.sql.DataSource" />
- 保存context.xml
- 打开hibernate-cfg.xml文件,添加和删除下面的属性。
Adding: ------- <property name="connection.datasource">java:comp/env/jdbc/mydb</property> Removing: -------- <!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> --> <!--<property name="connection.username">root</property> --> <!--<property name="connection.password"></property> -->
- 保存文件,并把最新的.WAR文件放在tomcat中。
- 重新启动tomcat。 数据库连接将工作。
我在使用c3p0 jar文件的IBM Websphere中遇到了同样的错误。 我有Oracle 10g数据库。 我只是使用Websphere Console在IBM Classpath中的Application Server JVM中添加了oraclejdbc.jar文件,并且错误已解决。
oraclejdbc.jar应该在您的服务器类path中设置您的C3P0 jar文件,无论它是IBM的tomcat,glassfish。