Somnath Guha
Somnath Guha

Reputation: 107

How to get DB connection state using JPA?

During the server start up(tomcat) I am creating an entitymangerfactory and storing into the memory. My question, is there any way I can check the connection state during this time?

What is happening now, it is creating an entitymangerfactory object during startup, but do not test whether has connected the database or not. With invalid configuration it is creating the entitymanagerfactory but when we are trying to execute some queries only then I am getting the exception.

What should I do if I want to check the connection state during server startup?

Thanks in advance

-regards, Somnath Guha

Upvotes: 0

Views: 930

Answers (2)

Gimby
Gimby

Reputation: 5274

Let me rephrase your question: during startup I want to know if I will be able to successfully execute queries. Forget about connection state, that's your ultimate goal - to execute JPA persistence stuff and not get connection errors.

So... during startup after you create your factory, obtain an EntityManager and try to execute a simple fetch. Seems obvious, no?

Upvotes: 0

MrSimpleMind
MrSimpleMind

Reputation: 8587

You should create a servlet that implements the ServletContextListener,

web.xml:

<listener>
  <listener-class>test.JPACheckServlet</listener-class>
</listener>

the code:

public class JPACheckServlet implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
    here put the code for checking the connection and report status, logging...
  }
  public void contextDestroyed(ServletContextEvent event) {
    here to handle fancy shutdown situation, loggings, etc 
  }
}

Good thread to read: How do servlets work? Instantiation, sessions, shared variables and multithreading

Upvotes: 1

Related Questions