Spring Boot + HikariCP
September 14, 2023
This page will walk through Spring Boot and HikariCP example. HikariCP is fast, simple, reliable and production ready JDBC connection pool. In Spring Boot 2.0 release, default database pooling technology has been switched from Tomcat Pool to HikariCP. This is because HikariCP offers superior performance. Now since Spring Boot 2.0 release, spring-boot-starter-jdbc
and spring-boot-starter-data-jpa
resolve HikariCP dependency by default and spring.datasource.type
property has HikariDataSource
as default value. Spring boot prefers HikariCP on first place then Tomcat pooling and then Commons DBCP2 on the basis of availability. Here on this page I will create a complete example of HikariCP with Spring Boot Data and MySQL. I will perform create and read operation in database. I will configure HikariCP properties such as connectionTimeout, minimumIdle, maximumPoolSize, idleTimeout, maxLifetime and autoCommit in application.properties
file.
Contents
Technologies Used
Find the technologies being used in our example.1. Java 20
2. Spring 6
3. Spring Boot 3
4. MySQL 8
HikariCP Dependency
Before using HikariCP, we need to make sure that we have resolved the HikariCP dependency. If we are using Maven we can use following dependency.<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>5.0.1</version> </dependency>
pom.xml
or build.gradle
ourselves because spring-boot-starter-jdbc
and spring-boot-starter-data-jpa
resolve it by default. It means if we are using dependencies either
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> <version>3.1.3</version> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>3.1.3</version> </dependency>
pom.xml
or build.gradle
.
HikariCP Configurations
For the Hikari connection pool configuration, we enable it by usingspring.datasource.type
and assigning it fully qualified name of the connection pool implementation in application.properties
file as following.
spring.datasource.type = com.zaxxer.hikari.HikariDataSource
HikariDataSource
by default and we need not to configure above line.
Now to configure Hikari specific connection pool settings, Spring Boot provides
spring.datasource.hikari.*
prefix to be used in application.properties
file. We will discuss here some frequently used configurations.
1. connectionTimeout
connectionTimeout
is the maximum number of milliseconds that a client will wait for a connection from connection pool. We need to configure it as following.
spring.datasource.hikari.connection-timeout=20000
minimumIdle
is the minimum number of idle connections that is maintained by HikariCP in connection pool. It is configured as following.
spring.datasource.hikari.minimum-idle=5
maximumPoolSize
configures the maximum pool size. It is configured as following.
spring.datasource.hikari.maximum-pool-size=12
idleTimeout
is the maximum amount of time in milliseconds that a connection is allowed to sit idle in connection pool. It is configured as following.
spring.datasource.hikari.idle-timeout=300000
maxLifetime
is the maximum life time in milliseconds of a connection in pool after it is closed. It is configured as following.
spring.datasource.hikari.max-lifetime=1200000
6. autoCommit
autoCommit
configures the default auto-commit behavior of connections returned from pool. Default value is true.
spring.datasource.hikari.auto-commit=true
Complete Example
We will create a Spring Boot REST web service with Spring Boot Data, HikariCP and MySQL. We will useCrudRepository
to query database. We will also create a REST client using RestTemplate
to test our application. First find the project structure of the demo application.

MySQL Table: articles
CREATE TABLE `articles` ( `article_id` INT NOT NULL AUTO_INCREMENT, `title` VARCHAR(200) NOT NULL, `category` VARCHAR(100) NOT NULL, PRIMARY KEY (`article_id`) )
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.1.3</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.1.0</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>javax.persistence-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.1.0</version> </dependency>
Now find the property file to configure datasource and other properties. Connection pool will be configured using HikariCP.
application.properties
spring.datasource.url=jdbc:mysql://localhost/cp spring.datasource.username=root spring.datasource.password=Mysql@1234 #Starting from Spring Boot 2.0 includes HikariDataSource by default #spring.datasource.type = com.zaxxer.hikari.HikariDataSource spring.datasource.hikari.connection-timeout=20000 spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.maximum-pool-size=12 spring.datasource.hikari.idle-timeout=300000 spring.datasource.hikari.max-lifetime=1200000 spring.datasource.hikari.auto-commit=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect spring.jpa.properties.hibernate.id.new_generator_mappings=false spring.jpa.properties.hibernate.format_sql=true
spring.datasource.type
property for HikariCP as following.
spring.datasource.type = com.zaxxer.hikari.HikariDataSource
ArticleRepository.java
package com.concretepage.repository; import org.springframework.data.repository.CrudRepository; import com.concretepage.entity.Article; public interface ArticleRepository extends CrudRepository<Article, Long> { }
package com.concretepage.entity; import java.io.Serializable; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; @Entity @Table(name="articles") public class Article implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "article_id") private long articleId; @Column(name = "title") private String title; @Column(name = "category") private String category; // setters and getters }
public interface IArticleService { List<Article> getAllArticles(); void addArticle(Article article); }
@Service public class ArticleService implements IArticleService { @Autowired private ArticleRepository articleRepository; @Override public List<Article> getAllArticles(){ List<Article> list = new ArrayList<>(); articleRepository.findAll().forEach(e -> list.add(e)); return list; } @Override public void addArticle(Article article){ articleRepository.save(article); } }
package com.concretepage.controller; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; public class ArticleInfo { @JsonInclude(Include.NON_NULL) private long articleId; @JsonInclude(Include.NON_NULL) private String title; @JsonInclude(Include.NON_NULL) private String category; //setters and getters }
@RestController @RequestMapping("user") public class ArticleController { @Autowired private IArticleService articleService; //Fetches all articles @GetMapping(value= "articles") public ResponseEntity<List<ArticleInfo>> getAllArticles() { List<ArticleInfo> responseArticleList = new ArrayList<>(); List<Article> articleList = articleService.getAllArticles(); for (int i = 0; i < articleList.size(); i++) { ArticleInfo ob = new ArticleInfo(); BeanUtils.copyProperties(articleList.get(i), ob); responseArticleList.add(ob); } return new ResponseEntity<List<ArticleInfo>>(responseArticleList, HttpStatus.OK); } //Creates a new article @PostMapping(value= "article") public ResponseEntity<Void> addArticle(@RequestBody ArticleInfo articleInfo, UriComponentsBuilder builder) { Article article = new Article(); BeanUtils.copyProperties(articleInfo, article); articleService.addArticle(article); HttpHeaders headers = new HttpHeaders(); headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED); } }
SpringBootAppStarter.java
@SpringBootApplication @EnableJpaRepositories("com.concretepage.repository") public class SpringBootAppStarter implements CommandLineRunner { @Autowired DataSource dataSource; public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootAppStarter.class, args); } @Override public void run(String... args) throws Exception { System.out.println("DataSource = " + dataSource); } }
Output
HikariPool-1 - Start completed.
RestClientUtil.java
public class RestClientUtil { public void getAllArticlesDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/articles"; HttpEntity<String> requestEntity = new HttpEntity<String>(headers); ResponseEntity<Article[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Article[].class); Article[] articles = responseEntity.getBody(); for(Article article : articles) { System.out.println("Id:"+article.getArticleId()+", Title:"+article.getTitle() +", Category: "+article.getCategory()); } } public void addArticleDemo() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user/article"; Article objArticle = new Article(); objArticle.setTitle("Spring REST Security using Hibernate"); objArticle.setCategory("Spring"); HttpEntity<Article> requestEntity = new HttpEntity<Article>(objArticle, headers); URI uri = restTemplate.postForLocation(url, requestEntity); System.out.println(uri.getPath()); } public static void main(String args[]) { RestClientUtil util = new RestClientUtil(); util.addArticleDemo(); util.getAllArticlesDemo(); } }
Output
Id:1, Title:Spring REST Security using Hibernate, Category: Spring
Test Application
To test the application, first create table in MySQL as given in the article and configure your database credentials inapplication.properties
file. Then we can run REST web service in following ways.
1. Using Maven Command: Download the project source code. Go to the root folder of the project using command prompt and run the command.
mvn spring-boot:run
2. Using Eclipse: Download the project source code using the download link given at the end of article. Import the project into eclipse. Using command prompt, go to the root folder of the project and run.
mvn clean eclipse:eclipse
SpringBootAppStarter
by clicking Run as -> Java Application. Tomcat server will be started.
3. Using Executable JAR: Using command prompt, go to the root folder of the project and run the command.
mvn clean package
java -jar target/spring-boot-app.jar
Now we are ready to test the application. To run web service client, go to the
RestClientUtil
class in eclipse and click on Run as -> Java Application.
References
1. Spring Boot Reference Guide2. HikariCP