Hibernate lento

5 respostas
kleins

Galera, boa noite...

Eu estava acostumado a usar o toplink no Glassfish, porém recentemente precisando fazer um sistema menor, e estou usando tomcat + hibernate.

Quando usava o toplink + glassfish, o gerênciador de persistência fazia o load das named queries e demais configurações uma vez apenas, já no tomcat + hibernate, aparentemente isso está acontecendo a todo momento que envio uma instrução e com isso a performance está péssima...

Olha o exemplo, no código abaixo, cliquei duas vezes em um botão que envia um insert pro banco.

Cadastrando...
11/08/2010 21:20:46 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.innova.entity.Executives
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findAll => SELECT e FROM Executives e
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByIdexecutives => SELECT e FROM Executives e WHERE e.idexecutives = :idexecutives
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByName => SELECT e FROM Executives e WHERE e.name = :name
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByTitle => SELECT e FROM Executives e WHERE e.title = :title
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByDegree => SELECT e FROM Executives e WHERE e.degree = :degree
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByInterest => SELECT e FROM Executives e WHERE e.interest = :interest
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByLastdegree => SELECT e FROM Executives e WHERE e.lastdegree = :lastdegree
11/08/2010 21:20:46 org.hibernate.cfg.annotations.QueryBinder bindQuery

MEIO <suprimi aqui>

INFO: Named query checking : enabled
11/08/2010 21:20:51 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
11/08/2010 21:20:51 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured


Cadastrando...
11/08/2010 21:20:58 org.hibernate.cfg.AnnotationBinder bindClass
INFO: Binding entity from annotated class: com.innova.entity.Executives
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findAll => SELECT e FROM Executives e
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByIdexecutives => SELECT e FROM Executives e WHERE e.idexecutives = :idexecutives
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByName => SELECT e FROM Executives e WHERE e.name = :name
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByTitle => SELECT e FROM Executives e WHERE e.title = :title
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByDegree => SELECT e FROM Executives e WHERE e.degree = :degree
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByInterest => SELECT e FROM Executives e WHERE e.interest = :interest
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery
INFO: Binding Named query: Executives.findByLastdegree => SELECT e FROM Executives e WHERE e.lastdegree = :lastdegree
11/08/2010 21:20:58 org.hibernate.cfg.annotations.QueryBinder bindQuery

MEIO <suprimi aqui>

INFO: Named query checking : enabled
11/08/2010 21:21:00 org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
11/08/2010 21:21:00 org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured

Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="innovaPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.innova.entity.Executives</class>
    <class>com.innova.entity.Gr</class>
    <class>com.innova.entity.Groups</class>
    <class>com.innova.entity.Institute</class>
    <class>com.innova.entity.Iproject</class>
    <class>com.innova.entity.Project</class>
    <class>com.innova.entity.Researcharea</class>
    <class>com.innova.entity.Researcher</class>
    <class>com.innova.entity.User</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="hibernate.connection.username" value="root"/>
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.connection.password" value="abc123"/>
      <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/in"/>
     <!-- <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/> -->
      <property name="hibernate.c3p0.max_size" value="5"/>
      <property name="hibernate.c3p0.min_size" value="1"/>
      <property name="hibernate.c3p0.timeout" value="5000"/>
      <property name="hibernate.c3p0.max_statements" value="100"/>
      <property name="hibernate.c3p0.idle_test_period" value="300"/>
      <property name="hibernate.c3p0.acquire_increment" value="2"/>
    </properties>
  </persistence-unit>
</persistence>

Valeuuuu

Um abraço.

5 Respostas

zoren

Estranho o seu log.

Por acaso vc não está criando o SessionFactory na hora de cadastrar, está?

Isso deixaria bem lento.

kleins

Bom dia Zoren!

É, pelo código acho que sim.

Qual seria a forma de criar uma vez só?

Um abs

public class ResearchareaJpaController {

    public ResearchareaJpaController() {
        emf = Persistence.createEntityManagerFactory("innovaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void save(Researcharea researcharea) throws PreexistingEntityException, Exception{

        EntityManager em = null;

        try {
            em = getEntityManager();

            em.getTransaction().begin();

                em.persist(researcharea);


            em.getTransaction().commit();

            em.close();
        } catch (Exception e) {
            System.out.println("Não Gravou "+e.getStackTrace()+"  "+e.getMessage()+"  "+e.getLocalizedMessage());

        }

    }
}
kleins

Vamos lá.

Criei uma classe que gerência isso, peguei um exemplo aqui do forum, ma smesmo assim ainda está lento e carregando a todo momento as queries e as confs, apesar do “Loading…” aparecer uma vez só, ou seja, ele está pegando a thread já aberta, porém ainda continua lento… :shock:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.innova.DAO;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author 
 */


public final class PersistenceUtil {

     private static final String UNIT_NAME = "innovaPU";

     private static EntityManagerFactory FACTORY;

     public static final ThreadLocal<EntityManager> SESSION = new ThreadLocal<EntityManager>();

     public static EntityManager currentEntityManager() {
         EntityManager manager = (EntityManager) SESSION.get();
         if (manager == null) {
             System.out.println("#################### Loading entityManager ######################");
             loadInstance();
             manager = FACTORY.createEntityManager();
             SESSION.set(manager);
         }
         return manager;
     }

     public static void closeEntityManager() {
         EntityManager manager = (EntityManager) SESSION.get();
          if (manager != null) {
              manager.close();
         }
         SESSION.set(null);
     }

     private static synchronized void loadInstance() {
         if (FACTORY == null) {
             FACTORY = Persistence.createEntityManagerFactory(UNIT_NAME);
         }
     }


 }
zoren

Eu uso essa

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;


import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author Felipe
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

ai vc faz no seu código:

Lento ele fica, mas apenas na primeira vez, que é quando está criando o sessionFactory, depois ele usa um que já exista

as sessões são leves então pode chamar diversas vezes que continua rapido

Enfim, na primeira vez que o sessionFactory estiver iniciando vai ficar devagar mesmo, mas nas outras vezes tem que ser rapido pq ele já está criado.

kleins

Grande Zoren

Acho que era mais influência da console do netbeans, pois fiz o Deploy no direto no tomcat e ficou rapido… :lol:

Valeu pela ajuda!

Um abraço.

Rodrigo

Criado 11 de agosto de 2010
Ultima resposta 12 de ago. de 2010
Respostas 5
Participantes 2