Estou utilizando o seguinte singleton para conexão ao banco de dados MySQL
public class DbConnectionFactory {
private static Connection connection;
private static Properties database;
private DbConnectionFactory(){
}
static{
try{
InputStream is = ServletController.class.getResourceAsStream("/database.properties");
database = new Properties();
database.load(is);
}catch (Exception e) {
throw new RuntimeException("Arquivo de propriedades responsável pela conexão com o banco de dados não foi encontrado");
}
}
public static Connection getInstance() throws Exception{
try{
if(connection == null){
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + database.getProperty("server") + ":"+ database.getProperty("port") +"/"+ database.getProperty("database") +"?serverTimezone=GMT-03:00",database.getProperty("user"),database.getProperty("password"));
connection.setAutoCommit(false);
}
}catch (Exception e) {
throw new Exception("Não foi possível conectar com o banco de dados. Erro: " + e.getMessage());
}
return connection;
}
}
Para iniciar a transação, faço o seguinte…
try{
DbConnectionFactory.getInstance();
process();
DbConnectionFactory.getInstance().commit();
}catch (Exception e) {
DbConnectionFactory.getInstance().rollback();
throw new ActionException(e.getMessage());
}
E nos DAOs faço:
PreparedStatement stmt = DbConnectionFactory.getInstance().prepareStatement("INSERT INTO .....
No meu computador…que o timeout do MySQL é gigante… funciona na boa… no servidor…o timeout é de 60 segundos… se ocorrer o timeout recebo o erro abaixo e só consigo reconectar se reiniciar a aplicação no Tomcat.
javax.servlet.ServletException: Communications link failure The last packet successfully received from the server was 255.066 milliseconds ago. The last packet sent successfully to the server was 24 milliseconds ago.