JNDI + tomcat + hibernate

0 respostas
W

Saudações galera.

Estou eu aqui as 03:05 da madrugada e o desespero já bateu.

estou a 2 semanas tentando concluir uma aplicação web uililazando hibernate e rodando em tomcat.

O problema está no pool de conexoes que não consigo controlar, depois de um tempo o tomcat envia esta mensagem:

03/11/2009 06:10:09 org.apache.tomcat.util.threads.ThreadPool logFull
SEVERE: All threads (200) are currently busy, waiting. Increase maxThreads (200) or check the servlet status
03/11/2009 07:17:01 org.apache.jk.common.ChannelSocket processConnection
WARNING: processCallbacks status 2

depois disso a navegação fica uma m3rd4.

Segui os conselhos do site https://www.hibernate.org/114.htm entre outros, mas não adiantou.
Depois de mexer muito meus arquivos de configuração estão assim:

context.xml em meta-inf/
<?xml version="1.0" encoding="UTF-8"?>
<Context>
  
   <Resource name="hibernate/SampleSessionFactory"
             auth="Container"
             removeAbandonedTimeout="30" maxActive="100"
   			 maxIdle="30" maxWait="10000"
             type="org.hibernate.SessionFactory"
             factory="hibernate.HibernateSessionFactoryTomcatFactory"
             configuration="hibernate.cfg.xml"/>
	
  
</Context>
web.xml em web-inf
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 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">
	
	
	
	<listener>
               <listener-class>hibernate.HibernateListener</listener-class>
	</listener>
	
	
	
        <resource-env-ref>
            <description>Sample Hibernate SessionFactory</description>
            <resource-env-ref-name>hibernate/SampleSessionFactory</resource-env-ref-name>
            <resource-env-ref-type>org.hibernate.SessionFactory</resource-env-ref-type>
       </resource-env-ref>
	 
          [outras configurações de mapeamento]...
	
	
</web-app>
<?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="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
          
    		<property name="hibernate.connection.password">[password]</property>
      		<property name="hibernate.connection.url">[url]</property>
        	<property name="hibernate.connection.username">[user]</property>
     
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
       
       <property name="c3p0.min_size">3</property>
       <property name="c3p0.max_size">5</property>
       <property name="c3p0.timeout">1800</property>
       
       
       <!-- Disable second-level cache. -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="cache.use_query_cache">false</property>
        <property name="cache.use_minimal_puts">false</property>
        <property name="max_fetch_depth">3</property>
    
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- aqui em diante só há mapeamento -->
       
    </session-factory>
</hibernate-configuration>
HibernateSessionFactoryTomcatFactory
public class HibernateSessionFactoryTomcatFactory implements ObjectFactory{
   public Object getObjectInstance(Object obj, Name name, Context cntx, Hashtable env) 
                 throws NamingException{

      SessionFactory sessionFactory = null;
      RefAddr addr = null;
      
      try{
         Enumeration addrs = ((Reference)(obj)).getAll();
            
         while(addrs.hasMoreElements()){
            addr = (RefAddr) addrs.nextElement();
            if("configuration".equals((String)(addr.getType()))){
               sessionFactory = (new Configuration()).configure((String)addr.getContent()).buildSessionFactory();
            }
         }
      }catch(Exception ex){
         throw new javax.naming.NamingException(ex.getMessage());
      }

      return sessionFactory;
   }
}
HibernateListener
public class HibernateListener implements ServletContextListener {

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

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

}
HibernateUtil
public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();
	private static SessionFactory buildSessionFactory() {
		try {
			
			Context initialCntx = new InitialContext();
			SessionFactory sessionFactory = (SessionFactory)initialCntx.lookup("java:comp/env/hibernate/SampleSessionFactory");
			return  sessionFactory;

//			as lisnhas abaixo correspondem a antiga configuração
//			Session hibernateSess = sessionFactory.getCurrentSession();
//
//			
//			Configuration cfg = new Configuration();
//			cfg.configure("hibernate.cfg.xml");
//			
//			
//			return  cfg.buildSessionFactory();
		}
		catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

eu crio as conexoes dessa forma:

Session session = HibernateUtil.getSessionFactory().opentSession();
		session.beginTransaction();	
		
		String html = "";
		List<Entity> list = session.createQuery("from Entity").list();
		session.getTransaction().commit();
		session.close();

Pessoal, eu sei que tem arquivo de configuração demais aí, mas foi sendo acrescentado aos poucos... pelo menos esá funcionando, o problema é o pool de conexôes.

Vocês sempre são demais, espero que possam me ajudar. se precisarem de mais algum código é só pedir.

Já não durmo mais. Se tiverem até mesmo uma receita de bolo eu to aceitando.

Se acharem que é mais facil fazer o lance todo em puro JDBC é só dá um toque pois tenho todos os DAOs guardados (a aplicação era em JDBC antes, mas apresentava problema similar).

até mais...

Criado 5 de novembro de 2009
Respostas 0
Participantes 1