Hibernate check connection to database in Thread ( every time period )

我怕爱的太早我们不能终老 提交于 2019-12-20 03:07:04

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/11674049/hibernate-check-connection-to-database-in-thread-every-time-period

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!