javaspringspring-bootdatabase-connectionconnection-pool

Spring boot connection pool understanding


In Spring boot application.properties file we have the following options:

server.tomcat.max-threads = 100
server.tomcat.max-connections = 100
spring.datasource.tomcat.max-active = 100
spring.datasource.tomcat.max-idle = 30

This is my repository class

public interface UserRepository extends JpaRepository<Users,Integer>{}

This is the service class

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;
    public User getUserById(Integer id){return userRepository.findOne(id)}

The question is, how userRepository create the connection to DB and will it use the connection pool from my application properties file. I come from JDBC and hibernate where I used DataManager, DataSource, Connection classes to use the connection pool, but in spring boot I didn't have any line of code with this classes and everything work fine


Solution

  • It works as it worked before but with Spring Boot, Spring makes more tasks for you.
    With or without Spring, DAO class as UserRepository doesn't manipulate directly the datasource and doesn't create directly the JDBC connections either.
    These are manipulated by the EntityManagerFactory implementation you are using.
    With Spring-Hibernate, you still had to configure the EntityManagerFactory.
    Now with Spring Boot, you don't need to configure it.
    It is done for you.

    The new thing of Spring Boot is that you can also configure the server datasource properties now :

    server.tomcat.max-threads = 100
    server.tomcat.max-connections = 100
    spring.datasource.tomcat.max-active = 100
    spring.datasource.tomcat.max-idle = 30
    

    as the Tomcat server can be started by the Spring Boot application itself.

    This part of the Spring Boot documentation gives the preference order of the datasource implementation :

    Production database connections can also be auto-configured using a pooling DataSource. Here’s the algorithm for choosing a specific implementation:

    We prefer the Tomcat pooling DataSource for its performance and concurrency, so if that is available we always choose it.

    Otherwise, if HikariCP is available we will use it.

    If neither the Tomcat pooling datasource nor HikariCP are available and if Commons DBCP is available we will use it, but we don’t recommend it in production and its support is deprecated.

    Lastly, if Commons DBCP2 is available we will use it.


    Update: As per Spring Boot 2.x, HikariCP is the default connection pool mechanism.