I am using spring-boot in my web application and use spring-jpa to read/write from/to my database. It works very well but I want to understand how to manage the database connect
When using DB connection pooling, a call to sqlconnection.close()
will not necessarily close the heavyweight connection to the database, instead most often will just release the connection as re-usable in the pool. That's why it is advisable to invoke the close()
on connection as soon as possible when leveraging a client side connection pool.
In your configuration, the pool will contain a maximum number of 500 connections ( it would be also good to configure maxIdle
, minIdle
, and minEvictableIdleTimeMillis
to tune the number of ready-to-use connections and how often to release them when not used).
Some more doc here
You have already found that you can configure this from application.properties
You can find all the possible properties here.
Notice that from Spring Boot 1.4 there are datasource properties for every datasource vendor that spring integrates with, out of the box. There is spring.datasource.dbcp.*
,spring.datasource.tomcat.*
and so on. See 1.4 docs
If that's not enought, and you need something very specific, you can declare the datasource bean yourself. Here is the example with Tomcat datasource:
@Bean
public DataSource dataSource(){
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://localhost:3306/mysql");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("password");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
return datasource ;
}