Tratar exceções na Conexão Hibernate

9 respostas
R

Tem como tratar as exceções de conexão do hibernate como no JDBC?

public Connection getConexao(){
		if(!isLeuProperties()){
			lerProperties();
		}
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://"+ host +":"+porta+"/"+bd;

		try {
			Class.forName(driver);
			Conexao = DriverManager.getConnection(url, usuario, senha);
			setConectado(true);
		} catch (ClassNotFoundException e) {
			setConectado(false);
			JOptionPane.showMessageDialog(null,
					"Classe do MySQL não encontrada.", "Erro",
					JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			setConectado(false);
			int codErro = e.getErrorCode();
			if(codErro == 0){
				JOptionPane.showMessageDialog(null,"Servidor do Banco de Dados não encontrado!\nVerifique suas Configurações ou Contate a eXPerience Softwares.", "Erro",JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}else if(codErro == 1049){
				JOptionPane.showMessageDialog(null,"Banco de Dados não foi encontrado!\nVerifique suas Configurações ou Contate a eXPerience Softwares.", "Erro",JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}else if(codErro == 1045){
				JOptionPane.showMessageDialog(null,"Login/Senha Inválidos ao Conectar com o Banco de Dados!\nVerifique suas Configurações ou Contate a eXPerience Softwares.", "Erro",JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}else{
				JOptionPane.showMessageDialog(null,e.getMessage() +"\nCódigo do erro:" + codErro  , "Erro",JOptionPane.ERROR_MESSAGE);
			}
		}
		return Conexao;
	}

9 Respostas

R

Ninguem??

rodrigoallemand

Quais exceções vc quer tratar?!? As mesma desse código?!?
Acho que não.
Porem o hibernate levanta uma exceção chamada HibernateException.
Mas vc pode colocar um try {} catch (Throwable e){} e pegar tudo de uma vez…

R

vc tem um exemplo?por favor

rodrigoallemand
Método para pegar uma conexão...
public static Session getCurrentSession(String configFile) throws HibernateException {
        Session session = threadSession.get();

		try {
			if (session == null || !session.isOpen()) {
				if (sessionFactory == null) {
					try {
						cfg.configure(configFile);
						sessionFactory = cfg.buildSessionFactory();
					} catch (Exception e) {
						throw e;
					}
				}
				session = (sessionFactory != null) ? sessionFactory.openSession() : null;
				threadSession.set(session);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}

        return session;
    }
R

Vlw…eh como vc faz pra saber se esta conectado ou nao…ou qual o SQLException q ele gera…

rodrigoallemand

Se a sua session estiver válida, ela está conectada!
Caso contrário, alguma exceção será levantada nesse método, por exemplo...

Segue meu HibernateSessionFactory pra te auxiliar...

public class HibernateSessionFactory {

	/**
	 * Construtor no-arg
	 * Protegido para evitar a criação da classe
	 */
	protected HibernateSessionFactory() {
		super();
	}

	/* Constante de caminho do arquivo de configuração do Hibernate */
    private static String DEFAULT_CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

    /* Threads que controlarão a sessão e a transação */
	private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
	private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();

	/* Variaveis do Hibernate */
    private static final Configuration cfg = new Configuration();
    private static SessionFactory sessionFactory;

    /**
     * Método que retorna a instancia da Sessão utilizando o arquivo default do hibernate (/hibernate.cfg.xml).
     * @return Session
     * @throws SessionFactoryException
     */
    public static Session getCurrentSession() throws HibernateException {
    	return HibernateSessionFactory.getCurrentSession(DEFAULT_CONFIG_FILE_LOCATION);
    }

    /**
     * Método que retorna a instancia da Sessão.
     * @return Session
     * @throws SessionFactoryException
     */
    public static Session getCurrentSession(String configFile) throws HibernateException {
        Session session = threadSession.get();

		try {
			if (session == null || !session.isOpen()) {
				if (sessionFactory == null) {
					try {
						cfg.configure(configFile);
						sessionFactory = cfg.buildSessionFactory();
					} catch (Exception e) {
						throw e;
					}
				}
				session = (sessionFactory != null) ? sessionFactory.openSession() : null;
				threadSession.set(session);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}

        return session;
    }

    /**
     * Método que fecha a sessão do Hibernate.
     * @throws SessionFactoryException
     */
    public static void doCloseSession() throws HibernateException {
        Session session = threadSession.get();
        threadSession.set(null);

        try {
			if (session != null) {
			    session.close();
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que inicia a transação do Hibernate.
     * @throws SessionFactoryException
     */
    public static void doBeginTransaction() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx == null){
				tx = getCurrentSession().beginTransaction();
				threadTransaction.set(tx);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que executa o rollback da transação.
     * @throws SessionFactoryException
     */
    public static void doRollback() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
				tx.rollback();
				threadTransaction.set(null);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que commita a transação.
     * @throws SessionFactoryException
     */
    public static void doCommit() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
				tx.commit();
				threadTransaction.set(null);
			}
		} catch (Exception e) {
			doRollback();
			throw new HibernateException(e);
		}
    }


}
R

Queria pegar o SQLException mas não to conseguindo...

O Código que vc me passou com umas alterações...

package com.experience.softwares.sgsc;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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

import com.experience.softwares.sgsc.model.Cliente;

public class HibernateSessionFactory {

	private static boolean LeuProperties = false;

	private static String host;
	private static String porta;
	private static String bd;
	private static String usuario;
	private static String senha;
	
	private static void lerProperties(){
		InputStream stream = HibernateUtility.class.getResourceAsStream("config.properties");  
		System.out.println("Leu Properties...");
		 Properties props = new Properties();
			try {
				props.load(stream);
				stream.close();
			}
			catch (IOException e) {
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		host = props.getProperty("mysql.host");
		porta = props.getProperty("mysql.port");
		bd = props.getProperty("mysql.bd");
		usuario = props.getProperty("mysql.user");
		senha = props.getProperty("mysql.password");
		setLeuProperties(true);
	}  
	
	protected HibernateSessionFactory() {
		super();
	}


    /* Threads que controlarão a sessão e a transação */
	private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
	private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();

	/* Variaveis do Hibernate */
    private static SessionFactory sessionFactory;

    /**
     * Método que retorna a instancia da Sessão utilizando o arquivo default do hibernate (/hibernate.cfg.xml).
     * @return Session
     * @throws SessionFactoryException
     */


    /**
     * Método que retorna a instancia da Sessão.
     * @return Session
     * @throws SessionFactoryException
     */
    public static Session getCurrentSession() throws HibernateException {
        Session session = threadSession.get();
       
		try {
			if (session == null || !session.isOpen()) {
				if (sessionFactory == null) {
					 if(!isLeuProperties()){
							lerProperties();
						}

				    	try {
				    		String url = "jdbc:mysql://"+ host +":"+porta+"/"+bd;

				    		AnnotationConfiguration cfg  = new AnnotationConfiguration();
				    		cfg.addAnnotatedClass(Cliente.class);
				    		cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
				            .setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
				            .setProperty("hibernate.connection.url", url)
				            .setProperty("hibernate.connection.username", usuario)
				            .setProperty("hibernate.connection.password", senha)
				            .setProperty("hibernate.show_sql", "true")
				            .setProperty("hibernate.format_sql", "true")
				    		.setProperty("hibernate.generate_statistics", "true")
				            .setProperty("hibernate.use_sql_comments", "true");
				    		
				    		sessionFactory = cfg.buildSessionFactory();  
					} catch (Exception e) {
						throw e;
					}
				}
				session = (sessionFactory != null) ? sessionFactory.openSession() : null;
				threadSession.set(session);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}

        return session;
    }

    /**
     * Método que fecha a sessão do Hibernate.
     * @throws SessionFactoryException
     */
    public static void doCloseSession() throws HibernateException {
        Session session = threadSession.get();
        threadSession.set(null);

        try {
			if (session != null) {
			    session.close();
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que inicia a transação do Hibernate.
     * @throws SessionFactoryException
     */
    public static void doBeginTransaction() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx == null){
				tx = getCurrentSession().beginTransaction();
				threadTransaction.set(tx);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que executa o rollback da transação.
     * @throws SessionFactoryException
     */
    public static void doRollback() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
				tx.rollback();
				threadTransaction.set(null);
			}
		} catch (Exception e) {
			throw new HibernateException(e);
		}
    }

    /**
     * Método que commita a transação.
     * @throws SessionFactoryException
     */
    public static void doCommit() throws HibernateException {
    	Transaction tx = threadTransaction.get();

    	try {
			if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack()){
				tx.commit();
				threadTransaction.set(null);
			}
		} catch (Exception e) {
			doRollback();
			throw new HibernateException(e);
		}
    }
    
    public static boolean isLeuProperties() {
		return LeuProperties;
	}

	public static void setLeuProperties(boolean leuProperties) {
		LeuProperties = leuProperties;
	}


}

Aonde eu pego a Exception???

To tentando aqui:

public class Teste {

//	static DaoFactory factory = new DaoFactory();  //  @jve:decl-index=0:
	//static ClienteDao dao =factory.getClienteDao();   //  @jve:decl-index=0:
	public static void main(String[] args) {

		try{
			 Session session = HibernateSessionFactory.getCurrentSession();
			 
			 if (!session.equals(null)){
			    	System.out.println("Banco De Dados: Conectado ");
			    }else{
			    	System.out.println("Banco De Dados: Desconectado ");
			    }
			  
		}catch(JDBCException e){
			SQLException sql = e.getSQLException();
			System.out.println("oi");
			System.out.println("Banco De Dados: Desconectado ");
		}
		
		
		    
			/*List<Cliente> clientes = dao.listaTudo();
			for (Cliente cliente : clientes) {
				System.out.println(cliente.getNome());
				System.out.println(cliente.getDtaCadastro());
			}
			Cliente oi = new Cliente();
			GregorianCalendar calendar = new GregorianCalendar();
			oi.setNome("José");
			oi.setDtaCadastro(calendar.getTime());
			dao.adiciona(oi);*/

		

	}

}

Mas ele n cai na Exception...

Precisava das Exception porque estou migrando do JDBC pro Hibernate e com o JDBC eu sabia pq ele n estava conectando dai n entrava no programa...

R

Mesmo ele não conectando a session abre de qualquer jeito…

R

N consegui ainda…
Mesmo n conectando ele diz q a session existe e está conectada

Criado 28 de novembro de 2007
Ultima resposta 30 de nov. de 2007
Respostas 9
Participantes 2