name example java hibernate jndi connection-pooling

java - example - Configure hibernate para conectarse a la base de datos a través de JNDI Datasource



spring hibernate jndi (4)

Configuración JNDI de Tomcat-7:

Pasos:

  1. Abra el servidor.xml en el directorio-tomcat / conf
  2. Agregue la etiqueta siguiente de <Resource> con los detalles de su DB dentro de <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. Guarde el archivo server.xml
  2. Abra el archivo context.xml en el directorio-tomcat / conf
  3. Agregue el siguiente <ResourceLink> dentro de la etiqueta <Context> .

<ResourceLink name="jdbc/mydb" global="jdbc/mydb" auth="Container" type="javax.sql.DataSource" />

  1. Guarde el contexto.xml
  2. Abra el archivo hibernate-cfg.xml y agregue y elimine las propiedades siguientes.

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. Guarde el archivo y ponga el último archivo .WAR en Tomcat.
  2. Reinicia el tomcat. la conexión DB funcionará.

Hola a todos, estoy utilizando Hibernate + Struts2 + Tomcat6 + Mysql como mi framework J2EE. He estado usando el mecanismo de agrupación de conexiones integrado de hibernate, pero resultó ser problemático cuando mysql cierra sus conexiones después de 8 horas. De todos modos busqué en Google un poco y descubrí que debería obtener mis conexiones a través del origen de datos JNDI, pero no pude llegar a un tutorial bueno y completo sobre esto. ¿Qué pasos debo tomar para hacerlo? por favor, dame suficientes detalles, soy un poco nuevo en esto. aquí está mi 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>

También probé esto pero no funcionó: crear un context.xml en WebContent / META-INF que contenga:

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

poniéndolo en 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>

y modificando la configuración de hibernación como esta:

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

como mencioné antes, no se conecta a la base de datos de esta manera. ¿algunas ideas?

[EDITAR] Cuando ejecuto la aplicación obtengo esta excepción:

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


Aparentemente, lo hiciste bien. Pero aquí hay una lista de cosas que necesitará con ejemplos de una aplicación en funcionamiento:

1) Un archivo context.xml en META-INF, especificando su origen de datos:

<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 que le dice al contenedor que está usando este recurso:

<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) Configuración de hibernación que consume la fuente de datos. En este caso, es un persistence.xml , pero es similar en 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>


Dentro del archivo applicationContext.xml de un proyecto de aplicación web maven Hibernet debajo de la configuración funcionó para mí.

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


Espero que ayude a alguien. ¡Gracias!


Obtuve el mismo error en mi IBM Websphere con archivos jar c3p0. Tengo la base de datos Oracle 10g. Simplemente agregué los archivos oraclejdbc.jar en la JVM del servidor de aplicaciones en IBM Classpath usando la consola de Websphere y se resolvió el error.

El oraclejdbc.jar se debe establecer con los archivos jar C3P0 en la ruta de clase del servidor, sea lo que sea tomcat, glassfish de IBM.