Hibernate - Dicas de desempenho

4 respostas
Z

Fala pessoal

To desenvolvendo um software de cadastros com hibernate so que toda vez que executo a primeira vez ele demora para cadastra, depois nao realiza as tarefas super rapido.

  1. Qualquer tipo de dicas de como melhora o desempenho do hibenate
  2. Como carrega o hibernate na inicialização do software

4 Respostas

fmeyer

o louds postou um otimo artigo sobre tunning de hibernate no blog dele

http://www.kumpera.net/blog/index.php/2006/09/29/guia-de-guerra-para-tunning-de-mapeamento-do-hibernate/

R

zerxxx, isto acontece porque, na primeira vez que você executa um comando do Hibernate, ele está iniciando a sessionFactory. Na execução dos próximos comandos ele executa rápido, visto que a sessionFactory já está inicializada.

Para resolver este problema você pode inicializar a sessionFactory na inicialização do seu sistema, desta forma o sistema demorará um pouco mais para ser iniciado, porém os comandos serão sempre executados com velocidade.

Espero ter ajudado.

Z

Valeu pessoal

aqui ta meu hibernate util

so que quero acrescenta 2 metodos um de cria Transaction e outro
de fechar Transaction,alquem sabe como

package br.hibernate.lib;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static Log log = LogFactory.getLog(HibernateUtil.class);

// o metodo static certifica-se de que o seseionFactory vai ser carregado
// apenas
// uma vez independe do nomero de usuario ou de sessões
private static final SessionFactory sessionFactory;

static {

try {

// Cria o SessionFactory

sessionFactory = new Configuration().configure(hibernate.cfg.xml)

.buildSessionFactory();

} catch (Throwable ex) {

// Cria um log caso haja uma exeção

log.error(Initial SessionFactory creation failed., ex);

throw new ExceptionInInitializerError(ex);

}

}

// cria uma thread para cada sessão executado.
public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() {

Session s = (Session) session.get();

// Open a new Session, if this Thread has none yet

if (s == null) {

s = sessionFactory.openSession();

session.set(s);

}

return s;

}
public static void closeSession() {

Session s = (Session) session.get();

if (s != null)

s.close();

session.set(null);

}

}
Z

Pessoal encontre o hibernate util do jeito que eu quero
so que nao entendi direito alquem pode explica ele

package Menu;

import org.hibernate.<em>;

import org.hibernate.cfg.Configuration;

import org.apache.commons.logging.</em>;

import javax.naming.*;

public class HibernateUtil {

private static Log log = LogFactory.getLog(HibernateUtil.class);

private static Configuration configuration;

private static SessionFactory sessionFactory;

private static final ThreadLocal threadSession = new ThreadLocal();

private static final ThreadLocal threadTransaction = new ThreadLocal();

private static final ThreadLocal threadInterceptor = new ThreadLocal();


static {
	try {
		configuration = new Configuration();
		sessionFactory = configuration.configure("hibernate.cfg.xml").buildSessionFactory();

	} catch (Throwable ex) {
		
		log.error("Building SessionFactory failed.", ex);
		throw new ExceptionInInitializerError(ex);
	}
}


public static SessionFactory getSessionFactory() {

	return sessionFactory;
}

public static Configuration getConfiguration() {
	return configuration;
}

/**
 * Rebuild the SessionFactory with the static Configuration.
 * 
 */
public static void rebuildSessionFactory() {
	synchronized (sessionFactory) {
		try {
			sessionFactory = getConfiguration().buildSessionFactory();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

/**
 * Rebuild the SessionFactory with the given Hibernate Configuration.
 * 
 * @param cfg
 */
public static void rebuildSessionFactory(Configuration cfg) {
	synchronized (sessionFactory) {
		try {
			sessionFactory = cfg.buildSessionFactory();
			configuration = cfg;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

/**
 * Retrieves the current Session local to the thread. <p/> If no Session is
 * open, opens a new Session for the running thread.
 * 
 * @return Session
 */
public static Session getSession() {
	Session s = (Session) threadSession.get();
	try {
		if (s == null) {
			log.debug("Opening new Session for this thread.");
			if (getInterceptor() != null) {
				log.debug("Using interceptor: "
						+ getInterceptor().getClass());
				s = getSessionFactory().openSession(getInterceptor());
			} else {
				s = getSessionFactory().openSession();
			}
			threadSession.set(s);
		}
	} catch (HibernateException ex) {
		ex.printStackTrace();
	}
	return s;
}

/**
 * Closes the Session local to the thread.
 */
public static void closeSession(){
	try {
		Session s = (Session) threadSession.get();
		threadSession.set(null);
		if (s != null && s.isOpen()) {
			log.debug("Closing Session of this thread.");
			s.close();
		}
	} catch (HibernateException ex) {
		ex.printStackTrace();
	}
}

/**
 * Start a new database transaction.
 */
public static void beginTransaction(){
	Transaction tx = (Transaction) threadTransaction.get();
	try {
		if (tx == null) {
			log.debug("Starting new database transaction in this thread.");
			tx = getSession().beginTransaction();
			threadTransaction.set(tx);
		}
	} catch (HibernateException ex) {
		ex.printStackTrace();
	}
}

/**
 * Commit the database transaction.
 */
public static void commitTransaction() {
	Transaction tx = (Transaction) threadTransaction.get();
	try {
		if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
			log.debug("Committing database transaction of this thread.");
			tx.commit();
		}
		threadTransaction.set(null);
	} catch (HibernateException ex) {
		rollbackTransaction();
		ex.printStackTrace();
	}
}

/**
 * Commit the database transaction.
 */
public static void rollbackTransaction() {
	Transaction tx = (Transaction) threadTransaction.get();
	try {
		threadTransaction.set(null);
		if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
			log
					.debug("Tyring to rollback database transaction of this thread.");
			tx.rollback();
		}
	} catch (HibernateException ex) {
		ex.printStackTrace();
	} finally {
		closeSession();
	}
}

/**
 * Reconnects a Hibernate Session to the current Thread.
 * 
 * @param session
 *            The Hibernate Session to be reconnected.
 */
public static void reconnect(Session session) {
	try {
		session.reconnect();
		threadSession.set(session);
	} catch (HibernateException ex) {
		ex.printStackTrace();
	}
}

/**
 * Disconnect and return Session from current Thread.
 * 
 * @return Session the disconnected Session
 */
public static Session disconnectSession(){

	Session session = getSession();
	try {
		threadSession.set(null);
		if (session.isConnected() && session.isOpen())
			session.disconnect();
	} catch (HibernateException ex) {
		ex.printStackTrace();
	}
	return session;
}

/**
 * Register a Hibernate interceptor with the current thread.
 * <p>
 * Every Session opened is opened with this interceptor after registration.
 * Has no effect if the current Session of the thread is already open,
 * effective on next close()/getSession().
 */
public static void registerInterceptor(Interceptor interceptor) {
	threadInterceptor.set(interceptor);
}

private static Interceptor getInterceptor() {
	Interceptor interceptor = (Interceptor) threadInterceptor.get();
	return interceptor;
}

}

Criado 2 de outubro de 2006
Ultima resposta 4 de out. de 2006
Respostas 4
Participantes 3