HIBERNATE: Problemas ao usar DataSource no TOMCAT

Ola á pessoal
Estou tentanto usar o Hibernate em uma pequena aplicação rodando no TOMCAT.
Ela rodou legal em uma aplicação desktop, mas quando tento usar com o TOMCAT fornecendo um DataSource…aí que as coisas complicam.

Eu estou recebendo uma mensagem que diz que nao consegui fazer o BIND do SessionFactory com o JNDI.

Aí quando tento acessar alguma pagina(mesmo com HTML puro) aparece uma pagina em branco.

Alguem tem alguma observação, dica ou sugestao???

Obrigado.

Seguem os codigos:

context.xml:

  <!-- The contents of this file will be loaded for each web application -->
<Context path="/Usuarios" reloadable="true" docBase="Usuarios" debug="5"
crossContext="true">

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <Resource name="jdbc/Usuarios"
              scope="Shareable"
              type="javax.sql.DataSource"
              auth="Celso"
              username="BLABLA"
              password="*****"
              driverClassName="oracle.jdbc.driver.OracleDriver"
              url="jdbc:oracle:thin:@192.168.1.150:1521:BLABLA"
              maxActive="8"
              maxIdle="8"
              maxWait="5000"/>
</Context>

web.xml:


<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
 version="2.4">

   <listener>
        <listener-class>listener.HibernateListener</listener-class>
    </listener>

   <display-name>Sistema Controle Usuario</display-name>
   <description>
      Descritor do contexto de desenvolvimento.
   </description>


   <servlet>
      <servlet-name>usuarios-invoker</servlet-name>
      <servlet-class>
         org.apache.catalina.servlets.InvokerServlet
      </servlet-class>
      <init-param>
         <param-name>debug</param-name>
         <param-value>0</param-value>
      </init-param>

   </servlet>


   <servlet-mapping>
      <servlet-name>usuarios-invoker</servlet-name>
      <url-pattern>/servlet/*</url-pattern>
   </servlet-mapping>


   <resource-ref>
                 <description>Tentativa de criar um Pool de Conexões usando as implementações do Próprio TOMCAT</description>
                 <res-ref-name>jdbc/Usuarios</res-ref-name>
                 <res-type>javax.sql.DataSource</res-type>
                 <res-auth>Celso</res-auth>
   </resource-ref>

</web-app>

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>
         <!--DIALETO DO BANCO(ORACLE)-->
         <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
         <!--DIALETO DO BANCO(ORACLE)-->

         <!-- CONFIGURACOES DE DEBUG-->
         <property name="hibernate.show_sql">true</property>
         <property name="hibernate.generate_statistics">true</property>
         <property name="hibernate.use_sql_comments">true</property>
         <property name="hibernate.format_sql">true</property>
         <!-- CONFIGURACOES DE DEBUG-->

         <!--BUSCANDO O DATASOURCE(DBCP) DO TOMCAT-->
         <property name="hibernate.connection.datasource">java:comp/env/jdbc/Usuarios</property>
         <!--BUSCANDO O DATASOURCE(DBCP) DO TOMCAT-->

         <!--DESABILITAR CACHE DE SEGUNDO NIVEL-->
         <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
         <!--DESABILITAR CACHE DE SEGUNDO NIVEL-->

         <!-- Bind the getCurrentSession() method to the thread. -->
         <property name="current_session_context_class">thread</property>
         <!-- Bind the getCurrentSession() method to the thread. -->

         <!--FONTE DE MAPEAMENTO-->
         <mapping resource="usuario/entidade/C01_ADM__GE__USUARIO.hbm.xml"/>
         <!--FONTE DE MAPEAMENTO-->
     </session-factory>
</hibernate-configuration>

C01_ADM__GE__USUARIO.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="usuario.entidade.C01_ADM__GE__USUARIO" table="C01_ADM__GE__USUARIO">
          <id name="C01_ADM_GE_USUA_CODIGO" type="string" column="C01_ADM_GE_USUA_CODIGO">
              <generator class="assigned"/>
          </id>
          <property name="C01_ADM_GE_USUA_SETOR"        type="string"    column="C01_ADM_GE_USUA_SETOR"/>
          <property name="C01_ADM_GE_USUA_NOME"         type="string"    column="C01_ADM_GE_USUA_NOME"/>
          <property name="C01_ADM_GE_USUA_SENHA"        type="string"    column="C01_ADM_GE_USUA_SENHA"/>
          <property name="C01_ADM_GE_USUA_CARGO"        type="string"    column="C01_ADM_GE_USUA_CARGO"/>
          <property name="C01_ADM_GE_USUA_ATENDE"       type="string"    column="C01_ADM_GE_USUA_ATENDE"/>
          <property name="C01_ADM_GE_USUA_SITUACAO"     type="integer"   column="C01_ADM_GE_USUA_SITUACAO"/>
          <property name="C01_ADM_GE_USUA_DATA"         type="timestamp" column="C01_ADM_GE_USUA_DATA"/>
          <property name="C01_ADM_GE_USUA_MATRICULA"    type="integer"   column="C01_ADM_GE_USUA_MATRICULA"/>
          <property name="C01_ADM_GE_USUA_ALTSENHA"     type="string"    column="C01_ADM_GE_USUA_ALTSENHA"/>
          <property name="C01_ADM_GE_USUA_HABILITADO"   type="string"    column="C01_ADM_GE_USUA_HABILITADO"/>
          <property name="C01_ADM_GE_USUA_CNH_REGISTRO" type="integer"   column="C01_ADM_GE_USUA_CNH_REGISTRO"/>
          <property name="C01_ADM_GE_USUA_CNH_CATEG"    type="string"    column="C01_ADM_GE_USUA_CNH_CATEG"/>
          <property name="C01_ADM_GE_USUA_STATUS_ATEND" type="string"    column="C01_ADM_GE_USUA_STATUS_ATEND"/>
          <property name="C01_ADM_GE_USUA_OPCAO"        type="string"    column="C01_ADM_GE_USUA_OPCAO"/>
          <property name="C01_ADM_GE_USUA_EMAIL"        type="string"    column="C01_ADM_GE_USUA_EMAIL"/>
          <property name="C01_ADM_GE_USUA_RAMAL"        type="string"    column="C01_ADM_GE_USUA_RAMAL"/>
          <property name="C01_ADM_GE_USUA_DTNASC"       type="timestamp" column="C01_ADM_GE_USUA_DTNASC"/>
   </class>

</hibernate-mapping>

HibernateListener.java(classe executada na inicialização do TOMCAT)

package listener;

import javax.servlet.*;
import util.HibernateUtility;

public class HibernateListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        HibernateUtility.getSessionFactory(); // Just call the static initializer of that class
    }

    public void contextDestroyed(ServletContextEvent event) {
        HibernateUtility.getSessionFactory().close(); // Free all resources
    }
}

HibernateUtility.java:

package util;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.apache.commons.logging.*;
import javax.naming.*;



public class HibernateUtility
{
    private static Log log = LogFactory.getLog(HibernateUtility.class);
    private static final SessionFactory factory;
    public static final ThreadLocal session = new ThreadLocal();

    static
    {
        try
        {
            //Cria a Fabrica de sessao a partir do hibernate.cfg.xml
            factory = new Configuration().configure().buildSessionFactory();
        }
        catch(Throwable e)
        {
            log.error("ERRO AO CRIAR A FABRICA DE SESSAO INICIAL.");
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Session currentSession() throws HibernateException
    {
        Session s = (Session) session.get();
        if (s==null)
        {
            s = factory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException
    {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
        {
            s.close();
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return factory;
    }


}

Mensagem no LOG:

14:58:20,758  INFO Environment:525 - using CGLIB reflection optimizer
14:58:20,768  INFO Environment:555 - using JDK 1.4 java.sql.Timestamp handling
14:58:21,429  INFO Configuration:1308 - configuring from resource: /hibernate.cfg.xml
14:58:21,429  INFO Configuration:1285 - Configuration resource: /hibernate.cfg.xml
14:58:23,743  INFO Configuration:469 - Reading mappings from resource: usuario/entidade/C01_ADM__GE__USUARIO.hbm.xml
14:58:24,694  INFO HbmBinder:309 - Mapping class: usuario.entidade.C01_ADM__GE__USUARIO -> C01_ADM__GE__USUARIO
14:58:25,065  INFO Configuration:1419 - Configured SessionFactory: null
14:58:25,746  INFO NamingHelper:26 - JNDI InitialContext properties:{}
14:58:25,776  INFO DatasourceConnectionProvider:61 - Using datasource: java:comp/env/jdbc/Usuarios
14:58:38,053  INFO SettingsFactory:77 - RDBMS: Oracle, version: Oracle8i Release 8.1.6.0.0 - Production
JServer Release 8.1.6.0.0 - Production
14:58:38,063  INFO SettingsFactory:78 - JDBC driver: Oracle JDBC driver, version: 10.1.0.2.0
14:58:38,274  INFO Dialect:103 - Using dialect: org.hibernate.dialect.OracleDialect
14:58:38,354  INFO TransactionFactoryFactory:34 - Transaction strategy: org.hibernate.transaction.JTATransactionFactory
14:58:38,374  INFO NamingHelper:26 - JNDI InitialContext properties:{}
14:58:38,384  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
14:58:38,384  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
14:58:38,394  INFO SettingsFactory:125 - Automatic flush during beforeCompletion(): disabled
14:58:38,394  INFO SettingsFactory:129 - Automatic session close at end of transaction: disabled
14:58:38,414  INFO SettingsFactory:136 - JDBC batch size: 15
14:58:38,414  INFO SettingsFactory:139 - JDBC batch updates for versioned data: disabled
14:58:38,434  INFO SettingsFactory:144 - Scrollable result sets: enabled
14:58:38,434  INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): disabled
14:58:38,434  INFO SettingsFactory:160 - Connection release mode: auto
14:58:38,444  INFO SettingsFactory:187 - Default batch fetch size: 1
14:58:38,454  INFO SettingsFactory:191 - Generate SQL with comments: enabled
14:58:38,464  INFO SettingsFactory:195 - Order SQL updates by primary key: disabled
14:58:38,474  INFO SettingsFactory:338 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
14:58:38,494  INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
14:58:38,494  INFO SettingsFactory:203 - Query language substitutions: {}
14:58:38,504  INFO SettingsFactory:209 - Second-level cache: enabled
14:58:38,504  INFO SettingsFactory:213 - Query cache: disabled
14:58:38,504  INFO SettingsFactory:325 - Cache provider: org.hibernate.cache.NoCacheProvider
14:58:38,534  INFO SettingsFactory:228 - Optimize cache for minimal puts: disabled
14:58:38,564  INFO SettingsFactory:237 - Structured second-level cache entries: disabled
14:58:38,634  INFO SettingsFactory:257 - Echoing all SQL to stdout
14:58:38,634  INFO SettingsFactory:264 - Statistics: enabled
14:58:38,634  INFO SettingsFactory:268 - Deleted entity synthetic identifier rollback: disabled
14:58:38,644  INFO SettingsFactory:283 - Default entity-mode: pojo
14:58:38,965  INFO SessionFactoryImpl:154 - building session factory
14:58:42,450  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured

pergunta estupida, mas vc lembrou de colocar o nome do datasource no config do hibernate?

Uai…
Coloquei sim, olha soh:

<property name="hibernate.connection.datasource">java:comp/env/jdbc/Usuarios</property>

experimente usar apenas …

jdbc/Usuarios

 <property name="hibernate.connection.datasource">java:jdbc/Usuarios</property>

Grande, fmeyer.

Nao rolou nao…agora deu outro tipo de erro, olha soh:

...
13:43:30,582 FATAL DatasourceConnectionProvider:55 - Could not find datasource: java:jdbc/Usuarios
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...

Valeu pela sugestao.

èu quando precisei criar esses data sources … coloquei no server.xml

Pois é…
Mas na propria documentação do TOMCAT fala que eh preferivel usar o META-INF/context.xml

Eu ja fiz umas aplicações aqui no mesmo esquema, sem usar o Hibernate, e funcionou belezinha.
Agora nao sei porque nao esta funcionando agora.

Fala moçada.
Blz??
Seguinte.
Eu fiz umas gambiarras por aqui.
No meu servlet Listener(HibernateListener.java) eu coloquei uns codigos depois que ele inicializa o SessionFactory.
Nestes codigos eu consegui recuperar um objeto do banco a partir do metodo C01_ADM__GE__USUARIOS.abre(String cod);

O que mais me intriga agora é que ao tentar acessar uma pagina JSP comum (apenas com comandos HTML) de dentro do TOMCAT ele me abre uma pagina em branco.
Sem nada!!!

Alguem tem alguma ideia do que pode estar acontecendo??

A solução do problema de vcs é simples , somente basta dar um HibernasteUtil.rebuildSessionFactory(); antes de por exemplo um usuarioDAOImpl.setSession(HibernateUtil.getSession());