Perdendo conexão com banco MySQL - hibernate

Pessoal,

tenho um página hospedada no KingHost, e frequentemente está ocorrendo o erro abaixo, me obrigando a toda vez reiniciar o TOMCAT.
Na minha máquina esse problema não ocorre, apenas no servidor que está hospedado.

Alguém sabe por que está ocorrendo esse erro? E como faço para solucioná-lo?

Obrigado

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was37102 seconds ago.The last packet sent successfully to the server was 37102 seconds ago, which is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

O último pacote recebido com sucesso do servidor foi a ‘X’ segundos atras… qual é o servidor mais longo configurado valor do ‘wait_timeout’. voce DEVE considerar qualquer sessão que venceu(expirou) e/ou em sua aplicação validar antes d testar a conexão. aumento (de algo) o servidor , valor para o timeout do cliente ou usando o Connector/J para evitar este problema…

Acredito eu que nao seja problema da sua aplicação, mas sim de seu BD MySQL…

Em um forum a possivel solução foi dada, tente: ta em ingles :smiley:

Regarding the one that’s working, it’s probably working because it isn’t
letting the connection sit idle for such a long time.

There are a few things you might want to consider:

  1. Just increase the connection timeout for your mysql service. The
    default is 8 hours. I have one third party app that keeps a connection
    for the life of an app (it doesn’t use pooling at all) and have pushed
    up the timeout to 25hrs on that so connections wouldn’t die during the
    normal Monday-Friday work week.

  2. Add the autoReconnect=true to the end of your jdbc url (note: this is
    not recommended by MySQL) and in the catch clause, re-establish the
    connection and try again.

  3. Put in the validationQuery in your Resource def. I know you said you
    didn’t want the extra overhead of a validaton query on every access, but
    it only takes an extremely small slice of time. Plus it only occurs
    when you get a connection. If you keep a connection for the life of
    your request, it only happens once per request. Please do close the
    connection and return it at the end of the request though.

Personally I’d just take the extremely tiny performance penalty of a
validaton query as the simplest solution.

veja aki tbm… em outro forum relatando o mesmo problema…
http://stackoverflow.com/questions/15949/javatomcat-dying-databse-connection

ja passei por isso, é um “problema” do hibernate e resolvi assim: http://blog.camilolopes.com.br/opensessionviewsolucao/ tem uma explicação do paulo da caelum tb sobre o assunto que é importante ler.

Pessoal,

obrigado pelas respostas, mas infelizmente não consegui evolução para corrigir meu problema. Pelo que entendi, minha aplicação está abrindo uma única conexão, e meu o MYSQL fecha ela após 8 horas. O correto seria eu estar fechando essas conexões com o banco e reabrindo. Como faço isso no DAO?

Segue abaixo codificação do meu DAO

[code]package dao;

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

public class DAOFactory {
private static DAOFactory instance;
private EntityManagerFactory emf;
private EntityManager em;
private UsuarioEmailDAO usuarioDAO;

public EntityManagerFactory getEmf() {
	return emf;
}


public DAOFactory() {
	emf = Persistence.createEntityManagerFactory("context");
	em = emf.createEntityManager();
	
	usuarioDAO = new UsuarioEmailDAO(em);	
}

public static DAOFactory getInstance(){
	if (instance == null){
		instance = new DAOFactory();
	}
	return instance;
}

public EntityManager getEm() {
	return em;
}

public UsuarioEmailDAO getUsuarioEmailDAO() {
	return usuarioDAO;
}

}
[/code]

obtenha a session e feche com o metodo do hibernate algo como:

getSession().getTransaction().close();