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

前端 未结 1 1201
轮回少年
轮回少年 2021-01-21 11:19

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\'v

1条回答
  •  清酒与你
    2021-01-21 11:43

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

    0 讨论(0)
提交回复
热议问题