我有一个在服务类中作为 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/