在服务器启动(tomcat)期间,我正在创建一个entitymangerfactory并存储到内存中。我的问题是,有什么方法可以检查这段时间的连接状态吗?
现在发生了什么,它在启动时创建一个entitymangerfactory对象,但不测试是否已连接数据库。使用无效的配置,它正在创建实体管理器工厂,但是当我们尝试执行一些查询时,我才会收到异常。
如果我想在服务器启动时检查连接状态,该怎么办?
提前致谢
-问候, 索姆纳特·古哈
最佳答案
您应该创建一个实现 ServletContextListener 的 servlet,
web.xml:
<listener>
<listener-class>test.JPACheckServlet</listener-class>
</listener>
代码:
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
}
}
值得一读的好帖子: How do servlets work? Instantiation, sessions, shared variables and multithreading
关于java - 如何使用JPA获取数据库连接状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18074535/