开发者

Verify database connection using Hibernate on startup

I have a desktop app where I'd like to test the validity of the connection between the app and the database. What is the best way to test this on startup of my app? At the moment trying to start a transaction and catching the exception seems to do the jo开发者_如何学运维b. Is there a better way?


I don't think this should be a job for Hibernate or your code. It should be built into the connection pool that you're using.

If you're deployed on a Java EE app server, this would be part of the JNDI connection pool configuration. You can ask it to check connections before doling them out with a query (e.g., "SELECT 1 FROM DUAL" for Oracle).

I'd recommend doing that outside of your app. Let a connection pool manage connections.


There can be configured an advanced connection pool with Hibernate, called c3p0. Just supply the configuration parameter in the persistence.xml:

<property name="hibernate.c3p0.testConnectionOnCheckout" value="true"/>

Hibernate will then try to access the neccessary classes. With Maven you configure:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>4.1.8.Final</version>
</dependency>

Note: I won't ignore that some say testing connections before using is expensive. I think the consistency of an application has advantage. And expensive is relative when executing real SQL statements, less than 10% even in simple cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜