web-dev-qa-db-ja.com

JNDIデータソースを介してデータベースに接続するように休止状態を構成する

こんにちは、J2EEフレームワークとしてHibernate + Struts2 + Tomcat6 + Mysqlを使用しています。私は休止状態のビルトイン接続プーリングメカニズムを使用してきましたが、mysqlが8時間後に接続を閉じると問題があることが判明しました。とにかく私は少しグーグルで調べて、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に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&amp;useUnicode=true&amp;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>

次のように休止状態の設定を変更します:

<?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>

前述したように、この方法ではデータベースに接続されません。何か案は?

[編集]アプリを実行すると、次の例外が発生します。

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
28
SJ.Jafari

どうやら、あなたはそれを正しくやった。しかし、実際のアプリケーションの例で必要なもののリストは次のとおりです。

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)データソースを消費するHibernate構成。この場合、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>
29
jpkrohling

Tomcat-7 JNDI設定:

手順:

  1. Tomcat-dir/confserver.xmlを開きます
  2. 以下に追加<Resource>タグ内のDBの詳細<GlobalNamingResources>
<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"/>
  1. server.xmlファイルを保存します
  2. context.xmlTomcat-dir/confで開きます
  3. 以下を追加<ResourceLink><Context>タグ。
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. context.xmlを保存します
  2. 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> -->
  1. ファイルを保存し、最新の.WARファイルをTomcatに配置します。
  2. Tomcatを再起動します。 DB接続が機能します。
8
MAA

設定の下にあるMaven Hibernet WebアプリプロジェクトのapplicationContext.xmlファイル内で機能しました。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


誰かに役立つことを願っています。ありがとう!

0
Anurag_BEHS

IBM Websphereでc3p0 jarファイルを使用して同じエラーが発生していました。 Oracle 10gデータベースがあります。 Websphereコンソールを使用してIBMクラスパスのアプリケーションサーバーJVMにoraclejdbc.jarファイルを追加しただけで、エラーは解決しました。

Oraclejdbc.jarは、Tomcat(IBMのglassfish)に関係なく、サーバークラスパスのC3P0 jarファイルで設定する必要があります。

0
Pankaj Mehra