Verify database connectivity with Hibernate at startup

I have a desktop application where I would like to check the connection between the application and the database. What is the best way to verify this when running my application? At the moment, trying to start a transaction and catch an exception seems to be doing the job. Is there a better way?

+3
source share
2 answers

I do not think this should be work for Hibernate or your code. It must be built into the connection pool that you are using.

If you are deployed to a Java EE application server, this will be part of the JNDI connection pool configuration. You can ask him to check the connections before throwing them out using a query (for example, "SELECT 1 FROM DUAL" for Oracle).

I would recommend doing this outside of your application. Let the connection pool manage the connections.

+3
source

An extended Hibernate connection pool called c3p0 can be configured. Just specify the configuration parameter in the persistence.xml file:

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

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

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

. , , . , . SQL, 10% .

0

Source: https://habr.com/ru/post/1783031/


All Articles