【发布时间】:2017-11-09 01:34:00
【问题描述】:
我有一个带有 Hibernate 和 Hikari 数据源的 Spring Boot 项目。 如果我有一些注入 SessionFactory 对象的功能来获取会话对象,那么几天后我对与 db 操作相关的任何方法都有这样的异常(只有重新启动才能解决这个问题):
org.springframework.transaction.CannotCreateTransactionException:
Could not open JPA EntityManager for transaction; nested exception is
javax.persistence.PersistenceException:
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection at
......
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 -
Connection is not available, request timed out after 30001ms.
似乎手动使用会话会导致此问题。 (我有类似的项目,具有相同的配置和功能,但没有注入 SessionFactory 和 Session ......我根本没有这样的问题)
application.yaml:
spring:
jpa:
properties:
hibernate:
dialect : org.hibernate.dialect.PostgreSQLDialect
current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
数据源配置
@EnableJpaRepositories("com.my.project.config")
@Configuration
public class DataSourceConfig {
@Inject
private AppProperties properties;
@Bean(name = "dataSource")
public DataSource dataSource() {
AppProperties.DatabaseProperties dbProps = properties.getDatabaseProperties();
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(org.postgresql.Driver.class.getName());
dataSource.setJdbcUrl(
dbProps.getProtocol().concat("://")
.concat(dbProps.getDbHost()).concat(":")
.concat(dbProps.getDbPort()).concat("/")
.concat(dbProps.getDbname())
);
dataSource.setUsername(dbProps.getUsername());
dataSource.setPassword(dbProps.getPassword());
dataSource.setMaximumPoolSize(30);
dataSource.setMinimumIdle(30);
return dataSource;
}
@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf) {
return hemf.getSessionFactory();
}
}
LogRepositoryImpl
@Repository
public class LogRepositoryImpl implements LogRepository {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<Log> getLogs(int offset, int count) {
Criteria criteria = getSession().createCriteria(Log.class);
return criteria.setFirstResult(offset).setMaxResults(count).list();
}
@Override
public void save(Log log) {
getSession().save(log);
}
private Session getSession() {
return sessionFactory.getCurrentSession();
}
}
dataSource.setMaximumPoolSize(30), dataSource.setMinimumIdle();没解决这个问题
【问题讨论】:
-
它是否适用于初始操作,但在一些成功的选择/保存后开始超时?
-
是的,第一次启动应用后,一切正常。
-
我知道时间已经过去了,但这是怎么结束的?
标签: hibernate spring-boot hikaricp