gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:13:22 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com