Reputation: 107
I have Java - Spring Boot - Hibernate - Postgres application. And hibernate creates database connection every request, why? Is there configurable? For example, for one session to last 10 minutes?
My Hibernate configuration:
@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 o.s.j.d.DriverManagerDataSource - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost:5432/monit]
Why? How can I change it?
Upvotes: 0
Views: 1544
Reputation: 1068
You need to configure connection pools manually since you define a DataSource. From Spring official documentation :
If you define your own DataSource bean, auto-configuration does not occur.
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
).
You can configure the maximum pool size with the following configuration with HikariCP
spring.datasource.hikari.maximum-pool-size= 10
Upvotes: 3