버전 비교

  • 이 줄이 추가되었습니다.
  • 이 줄이 삭제되었습니다.
  • 서식이 변경되었습니다.

목차

HikariCP Connection 설정하기

HikariCP는 가장 대중적으로 많이 사용하는 고성능 JDBC Connection Pool입니다. 이것을 사용하기 위해서는 src/main/resources/application.yml 파일에 다음과 같이 설정값들을 

코드 블럭
spring:
  application:
    name: HelloWorld

  ###################
  ## JDBC
  ###################

  datasource:
    hikari:
      jdbc-url: jdbc:postgresql://localhost:5432/test
      username: postgres
      password: postgres
      driver-class-name: org.postgresql.Driver
      connection-test-query: SELECT 1
      maximum-pool-size: 10
      minimum-idle: 3
    sql-script-encoding: UTF-8
    continue-on-error: true
    initialization-mode: always

Spring Boot JDBC Starter 추가하기

데이터베이스를 사용하려면 다음과 같이 Spring Boot JDBC Starter를 Maven POM인 pom.xml 파일에 추가하도록 합니다.

코드 블럭
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

HikariCP 추가하기

HikariCP를 사용하기 위해서는 다음과 같이 JDBC Driver와 HikariCP를 mvnrepository.com에서 찾아서 Maven POM인 pom.xml 파일에 추가하도록 합니다.

코드 블럭
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>${hikaricp.version}</version>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>${postgres.jdbc.version}</version>
</dependency>

DataSource 정의

이제 다음과 같이 DataSource와 JDBC Template을 정의합니다.

코드 블럭
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class DataSourceConfiguration {

    @Bean(name = "dataSource")
    @Primary
    @ConfigurationProperties("spring.datasource.hikari")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean
    JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

}