I am learning JPA w/Hibernate using a Java SE 6 project. I’d simply like to be able to detect if the connection between Hibernate and my database (MS SQL Server) is open. For example, I’d like to be able to detect this, log it, and try reconnecting again in 60 seconds.
This is what I thought would work but isOpen() doesn’t appear to be what I want (always is true):
EntityManagerFactory emf = Persistence.createEntityManagerFactory("rcc", props);
if (emf != null && emf.isOpen()) {
EntityManager em = emf.createEntityManager();
if (em == null || !emf.isOpen())
// error connecting to database
else ...
This seems to me to be a simple problem, but I cannot find an answer!
You could indeed use
getDelegate()to get the underlying provider object for the EntityManager and then access the underlying JDBCConnection. But read carefully the javadoc:This makes your code doubly non portable. First it ties you to the underlying implementation (Hibernate’s
Sessionhere). Second, you may not always get the same result (at least not in an Java EE container).Really, you don’t want this as this totally defeats the point of JPA. Plus, you don’t want to handle this low level connection verification yourself.
No, instead, you should use a (standalone) connection pool that will take care of that for you. c3p0 is one of them and it can be configured for connection testing and logging. Going the connection pool way means less code, better reliability, better recovery capabilities, better checks, without loosing portability. This looks like a 100% win-win situation to me.