简体   繁体   English

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

[英]Why Hibernate creates new database connection every request?

I have Java - Spring Boot - Hibernate - Postgres application.我有 Java - Spring 引导 - Hibernate - Postgres 应用程序。 And hibernate creates database connection every request, why? hibernate 每次请求都会创建数据库连接,为什么? Is there configurable?有可配置的吗? For example, for one session to last 10 minutes?例如,对于一个 session 持续 10 分钟?

My Hibernate configuration:我的 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;
}

And every request I'm getting following log:我收到以下日志的每个请求:

11:19:13.584 [http-nio-8080-exec-2] DEBUG osjdDriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/monit]

Why?为什么? How can I change it?我怎样才能改变它?

You need to configure connection pools manually since you define a DataSource.由于定义了 DataSource,因此需要手动配置连接池。 From Spring official documentation :来自Spring 官方文档

If you define your own DataSource bean, auto-configuration does not occur.如果您定义自己的 DataSource bean,则不会发生自动配置。

Starting from spring boot 2, HikariCP is the default Connection Pool embedded with spring boot starter ( spring-boot-starter-jdbc and spring-boot-starter-data-jpa ).从 spring 启动 2 开始, HikariCP是嵌入 spring 启动启动器( spring-boot-starter-jdbcspring-boot-starter-data-jpa )的默认连接池。

You can configure the maximum pool size with the following configuration with HikariCP您可以使用HikariCP使用以下配置配置最大池大小

spring.datasource.hikari.maximum-pool-size= 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM