Hibernate check connection to database in Thread ( every time period )
Use a connection pool like c3p0 or dbcp. You can configure such pool to monitor connections in pool - before passing connection to Hibernate, after receiving it back or periodically. If the connection is broken, the pool with transparently close it, discard and open a new one - without you noticing.
Database connection pools are better suited for multi-user, database heavy application where several connections are opened at the same time, but I don't think it's an overkill. Pools should work just fine being bound to max 1 connection.
UPDATE: every time you try to access the database Hibernate will ask the DataSource
(connection pool). If no active connection is available (e.g. because database is down), this will throw an exception. If you want to know in advance when database is unavailable (even when user is not doing anything), unfortunately you need a background thread checking the database once in a while.
However barely opening a session might not be enough in some configurations. You'll better run some dummy, cheap query like SELECT 1
(in raw JDBC).
Related videos on Youtube
kingkong
Updated on June 04, 2022Comments
-
kingkong almost 2 years
What is best/good/optimal way to monitor connection to database. Im writing swing application. What I want it to do is to check connection with database every time period. I've tried something like this.
org.hibernate.Session session = null; try { System.out.println("Check seesion!"); session = HibernateUtil.getSessionFactory().openSession(); } catch (HibernateException ex) { } finally { session.close(); }
But that dosn't work. Second question which is comming to my mind is how this session closing will affect other queries.
-
kingkong almost 12 yearsWhat in case connection is lost for more than 5 minutes. How can I inform user interface about it ?
-
kingkong almost 12 yearsThanks A LOT!! Work just fine.
-
amphibient over 10 yearsI am working this particular issue myself. How do I tell
c3p0
to close/disconnect my Hibernate session once the database is down? Also please see stackoverflow.com/questions/19645509/…