【发布时间】:2017-07-15 05:34:02
【问题描述】:
我们正在使用 Spring 4.2.5、Hibernate 4.1.4、MYSql 来构建 REST 服务。我们面临着非常奇怪的问题,无法理解到底发生了什么并且出现以下错误:
从服务器成功接收的最后一个数据包是 43417 秒前。最后一个成功发送到服务器的数据包是 43417 秒前,比服务器配置的“wait_timeout”值长。您应该考虑在应用程序中使用之前使连接失效和/或测试连接有效性,增加客户端超时的服务器配置值,或使用 Connector/J 连接属性“autoReconnect=true”来避免此问题。
为了获得数据库连接,我们使用基于 java 的配置,如下所示:
@Configuration
@EnableTransactionManagement
@ComponentScan({ "api.configuration" })
public class HibernateConfiguration {
@Autowired
private Environment environment;
private static final Logger logger = LoggerFactory.getLogger(HibernateConfiguration.class);
@Bean
public LocalSessionFactoryBean sessionFactory() throws PropertyVetoException {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "api.domain" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?autoReconnect=true");
dataSource.setUsername("test");
dataSource.setPassword("test");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("connection.autoReconnect", "true");
properties.put("connection.autoReconnectForPools","true");
properties.put("connection.is-connection-validation-required", "true");
return properties;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "api.domain" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(hibernateProperties());
return em;
}
@Bean
public PlatformTransactionManager transactionManager() throws PropertyVetoException{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject() );
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
}
google了一下,发现我们可以通过添加以下两个属性来解决这个问题:
<property name=”validationQuery” value=”SELECT 1″ />
<property name=”testOnBorrow” value=”true” />
由于我们使用 java 配置而不是基于 XML,我们不知道在 java 类中为 validationQuery 和 testOnBorrow 添加的确切属性名称,因为我们有 hibernate.show_sql
请推荐
【问题讨论】: