【问题标题】:How to get DB connection state using JPA?如何使用 JPA 获取数据库连接状态?
【发布时间】:2013-08-07 03:02:16
【问题描述】:

在服务器启动(tomcat)期间,我正在创建一个实体管理器工厂并将其存储到内存中。我的问题,有什么办法可以在这段时间内检查连接状态吗?

现在是什么情况,在启动的时候创建了一个entitymangerfactory对象,但是不测试是否连接了数据库。由于配置无效,它正在创建 entitymanagerfactory,但是当我们尝试执行一些查询时,我才得到异常。

如果我想在服务器启动过程中检查连接状态怎么办?

提前致谢

-问候, 索姆纳特·古哈

【问题讨论】:

  • 你试过connection.isValid(int Timeout)吗?如果通过发送一些查询本身连接是有效的,这将返回。

标签: java database hibernate jpa hibernate-entitymanager


【解决方案1】:

您应该创建一个实现 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

【讨论】:

    【解决方案2】:

    让我重新表述您的问题:在启动期间,我想知道我是否能够成功执行查询。忘记连接状态,这是您的最终目标 - 执行 JPA 持久性内容并且不会出现连接错误。

    所以...在创建工厂后的启动过程中,获取一个 EntityManager 并尝试执行一个简单的提取。看起来很明显,不是吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多