java - 为什么 Hibernate 每次请求都创建新的数据库连接?

标签 java postgresql hibernate spring-boot

我有 Java - Spring Boot - Hibernate - Postgres 应用程序。 hibernate 每次请求都会创建数据库连接,为什么?有可配置的吗?例如,一个 session 持续 10 分钟?

我的 hibernate 配置:

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "monitoring" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
    dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
    dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("spring.jpa.properties.hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("spring.jpa.hibernate.show-sql"));
    properties.put("hibernate.format_sql", "false");
    properties.put("hibernate.jdbc.lob.non_contextual_creation", "true");
    return properties;
}

我收到的每个请求都遵循日志:

11:19:13.584 [http-nio-8080-exec-2] DEBUG o.s.j.d.DriverManagerDataSource - 创建新的 JDBC DriverManager 连接到 [jdbc:postgresql://localhost:5432/monit]

为什么?我该如何更改它?

最佳答案

由于定义了数据源,因此需要手动配置连接池。 来自 Spring official documentation :

If you define your own DataSource bean, auto-configuration does not occur.

从spring boot 2开始,HikariCP是内嵌spring boot starter(spring-boot-starter-jdbcspring-boot- starter-data-jpa).

您可以使用 HikariCP

使用以下配置来配置最大池大小
spring.datasource.hikari.maximum-pool-size= 10

关于java - 为什么 Hibernate 每次请求都创建新的数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007799/

相关文章:

java - 如何在Spring框架中的Hibernate一对多关系中仅从父类获取json数据

java - Hibernate @Generate(GenerationType.ALWAYS) 不会在更新时填充我的时间戳

java - 如何模拟不是过滤器方法输入的 HttpServletRequest

java - 如何在堆叠条形图中添加范围轴标签

java - 将 BufferedImage 转换为 aws...rekognition.model.Image

java - 获取当前文件路径

java - 使用 JDBI 将二维数组插入 PostreSQL DB?

sql - && 运算符改变结果的顺序

postgresql - 由于 hstore,表上的 pg_restore 失败

java - native 查询 INSERT 给出错误 : Method is only allowed for a Query