OK, after of few days of work I have constructed a solution.
The problem was that just typical Hibernate session did not throw any exception while using it without database connected. But this piece of code does throw an exception when database not connected (so it can be used as a test):
Properties p = hibernateConnection.getCfg().getProperties();
String url = p.getProperty("hibernate.connection.url");
String user = p.getProperty("hibernate.connection.username");
String password = p.getProperty("hibernate.connection.password");
DriverManager.getConnection(url, user, password).close();
So, simple try-catch can be used. If an exception is caught, connection is dead.
I used this for regular checking of database connection. On application deploy, a TimerTask
is scheduled to run every minute. When it catches an exception, it sets a static variable dbAvailable
to false (otherwise to true). This variable is being checked on every HTTP client request and if it's true, error 503
is sent back in response.
For scheduling the timer I used ServletContextListener
. C3P0 configuration mentioned in the question.