/* This is not the entire class file, but just the methods that will handle the broken pipe connection problem */ public static final ThreadLocal session = new ThreadLocal(); public static Session getHibernateSession() throws EyeSystemException { Session session = null; /* If a broken pipe condition happens try to reconnect but if really there was some communication issue or the database is down, cannot keep reconnecting, so attempt it 5 times, if it doesn't then its Fatal. */ int connectionTries = 5; do { try { session = HibernateApp.getHibernateSession(); final Transaction transaction = session.beginTransaction(); /* A simple query that can actually test if the connection is valid, doesn't involve any schema selection hence there is a very minor performance hit */ session.createSQLQuery( "select 1" ).list(); transaction.commit(); return session; } catch ( TransactionException te ) { // Handle Transaction Exception } catch ( SQLException sqle ) { // Handle SQL Exception } catch ( NamingException ne ) { // Handle Naming Exception } catch ( GenericJDBCException gjdbce ) { /* This is where we need to look for the reason for error. SQL State 08S01 represents broken pipe. */ if ( gjdbce.getSQLState() == null || gjdbce.getSQLState().equals( "08S01" ) ) { // Use the reconnect method from the same class try { HibernateUtil.reconnect(); } catch (HibernateException) { // We have exception establishing connection again // Just allow it to go through 5 attempts } } } connectionTries = connectionTries - 1; } while ( connectionTries > 0 ); /* Should not come here at all, meaning we were unable to connect at all to the database even after 5 attempts. Throw Fatal. */ } public static void reconnect() throws HibernateException { Session s = ( Session ) HibernateApp.session.get(); HibernateApp.session.set( null ); s = HibernateApp.sessionFactory.openSession(); s.connection().setAutoCommit( true ); HibernateApp.session.set( s ); }