java - 连接丢失后自动重新连接 JPA EntityManager

标签 java spring hibernate postgresql jpa

我有一个在服务类中作为 Autowiring 对象调用的 EntityManager bean 对象。

Spring 配置类:

@EnableWebMvc
@Configuration("myWebConfiguration")
@ComponentScan(basePackages = {"org.my.app"})
@EnableScheduling
public class MyWebConfiguration extends WebMvcConfigurerAdapter {

....

    private static EntityManager entityManager; 

    @Bean
    public EntityManager entityManager() {
        if (entityManager == null) {
            entityManager = managerFactoryBean().getObject().createEntityManager();
        }
        return entityManager;
    }    

....

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.format_sql", "true");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");
        return properties;
    }

....

}

示例服务类:

@Service("sampleService")
public class SampleService {

    @Autowired
    protected EntityManager entityManager;

    public Object find(Class entityClass, Object id) {
        return entityManager.find(entityClass, id);
    }

    ....

}

还有问题:

如果 WebApp 服务器和数据库服务器之间的连接丢失,JPA 和 spring 无法重新连接到数据库服务器并且调用 entityManager 方法会导致异常,例如 org.postgresql.util.PSQLException: This connection has been closed.org.hibernate.exception.JDBCConnectionException: 无法检查 JDBC 自动提交模式

是否可以自动检测连接丢失并在连接丢失的情况下重新建立连接?

最佳答案

这是可能的,这是连接池(或支持连接池的数据源)库履行的职责。

例如,如果您使用 DBCP ,您可以设置 validationQuery="SELECT 1"testOnBorrow="true" 等参数,以允许检测连接状态并在需要时重新打开。

同样,c3p0允许使用 c3p0.testConnectionOnCheckout=true 等配置此类参数。

其他连接池库会公开类似的配置。

如果您已经在使用连接池库(或使用连接池的数据源),您可能需要查看其文档以获取要设置的相关配置属性。如果没有,您可能需要考虑使用连接池库或使用连接池并公开这些参数的数据源。

更新: 对于 c3p0,您可以添加以下属性并进行测试吗:

properties.setProperty("hibernate.c3p0.preferredTestQuery","SELECT 1");
properties.setProperty("hibernate.c3p0.testConnectionOnCheckout","true");

关于java - 连接丢失后自动重新连接 JPA EntityManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36370722/

相关文章:

java - 如何知道java中JRadioButton是否启用

java - 当我的编译器告诉我正在使用不安全或未经检查的操作时,这意味着什么?

Spring ws : No adapter for endpoint

Java 代码执行难题——跳行而不抛出异常

java - 如何在 spring-boot 和 postgresql 中使用 postgis 类型地理?

postgresql - Hibernate 3.4 到 5.1 迁移的 hibernate.hbm2ddl.auto 值 ="update"问题

java - 有没有办法在 hibernate 中选择额外的字段(不保存)?

java - 如何在android中安全地停止线程?

java - jsp调用其他类的函数

css - spring boot,Bootstrap不渲染bootstrap风格的页面