SpringブートJDBC MySQL HikariCPの例

Spring Boot JDBC + MySQL + HikariCPの例

この記事では、Spring Boot JDBCアプリケーション+ MySQLおよびHikariCPを作成する方法を示します。

この記事で使用されるツール:

  1. Spring Boot 1.5.1.RELEASE

  2. MySQL 5.7.x

  3. HikariCP 2.6

  4. メーベン

  5. Java 8

1. プロジェクト構造

標準のMavenプロジェクト構造。

spring boot jdbc directory

2. プロジェクトの依存関係

JDBCアプリケーションのspring-boot-starter-jdbcを宣言します。

pom.xml


    4.0.0

    com.example
    spring-boot-jdbc
    jar
    1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.1.RELEASE
    

    
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
            
                
                    org.apache.tomcat
                    tomcat-jdbc
                
            
        

        
        
            com.zaxxer
            HikariCP
            2.6.0
        

        
        
            mysql
            mysql-connector-java
            5.1.40
        

    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            

        
    

ターミナル

$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring-boot-jdbc 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ spring-boot-jdbc ---
[INFO] com.example:spring-boot-jdbc:jar:1.0
[INFO] +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.3.6.RELEASE:compile
[INFO] |  |     +- org.springframework:spring-aop:jar:4.3.6.RELEASE:compile
[INFO] |  |     \- org.springframework:spring-expression:jar:4.3.6.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] |  |  |  \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.22:compile
[INFO] |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] |  +- org.springframework:spring-core:jar:4.3.6.RELEASE:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.5.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-jdbc:jar:4.3.6.RELEASE:compile
[INFO] |     +- org.springframework:spring-beans:jar:4.3.6.RELEASE:compile
[INFO] |     \- org.springframework:spring-tx:jar:4.3.6.RELEASE:compile
[INFO] +- com.zaxxer:HikariCP:jar:2.6.0:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.22:compile
[INFO] \- mysql:mysql-connector-java:jar:5.1.40:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.164 s
[INFO] Finished at: 2017-02-12T23:42:47+08:00
[INFO] Final Memory: 20M/309M
[INFO] ------------------------------------------------------------------------

Database Connection Pooling
Spring BootはデフォルトでTomcatプーリングtomcat-jdbcを使用し、次のシーケンスに従って接続プールを見つけます。

Tomcat pool -->> - HikariCP -->>  Commons DBCP -->>  Commons DBCP2

この公式のSpringBootドキュメントを読む–Connection to a production database

3. JdbcTemplate

3.1 Spring Boot will register a JdbcTemplate bean automatically, injects it via @Autowired

CustomerRepository.java

package com.example.dao;

import com.example.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public class CustomerRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // Find all customers, thanks Java 8, you can create a custom RowMapper like this :
    public List findAll() {

        List result = jdbcTemplate.query(
                "SELECT id, name, email, created_date FROM customer",
                (rs, rowNum) -> new Customer(rs.getInt("id"),
                        rs.getString("name"), rs.getString("email"), rs.getDate("created_date"))
        );

        return result;

    }

    // Add new customer
    public void addCustomer(String name, String email) {

        jdbcTemplate.update("INSERT INTO customer(name, email, created_date) VALUES (?,?,?)",
                name, email, new Date());

    }


}

3.2 Customer Model.

Customer.java

package com.example.model;

import java.util.Date;

public class Customer {

    int id;
    String name;
    String email;
    Date date;

    public Customer(int id, String name, String email, Date date) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.date = date;
    }

    //getters and setters and toString...
}

4. データベースの初期化

Spring Bootは、デフォルトでdataSource初期化子を有効にし、クラスパスのルートからSQLスクリプト(schema.sqlおよびdata.sql)をロードします。

4.1 Create a customer table.

schema.sql

DROP TABLE IF EXISTS customer;
CREATE TABLE customer (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) NOT NULL,
  created_date DATE NOT NULL,
  PRIMARY KEY (id));

4.2 Insert 3 rows into the customer table.

data.sql

INSERT INTO customer(name,email,created_date)VALUES('example','[email protected]', '2017-02-11');
INSERT INTO customer(name,email,created_date)VALUES('yflow','[email protected]', '2017-02-12');
INSERT INTO customer(name,email,created_date)VALUES('zilap','[email protected]', '2017-02-13');

Note
詳細については、この公式記事–Spring Database initializationを参照してください。

4.3 To log the SQL scripts above, enable debug for org.springframework.jdbc

logback.xml



    

    
        
            
                %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
            
        
    

    
        
    

    
        
    

    
        
    

5. 設定

MySQLとHikariCP settingsを構成します。

application.properties

#disbale Spring banner
spring.main.banner-mode=off

# Loads SQL scripts? schema.sql and data.sql
#spring.datasource.initialize=true

spring.datasource.url=jdbc:mysql://localhost/example?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# HikariCP settings
# spring.datasource.hikari.*

#60 sec
spring.datasource.hikari.connection-timeout=60000
# max 5
spring.datasource.hikari.maximum-pool-size=5

6. @SpringBootApplication

Spring BootコンソールまたはCommandLineRunnerアプリケーションは、引数を受け入れて「表示」または「挿入」機能を実行します。

SpringBootConsoleApplication.java

package com.example;

import com.example.dao.CustomerRepository;
import com.example.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.sql.DataSource;
import java.util.List;

import static java.lang.System.exit;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    @Autowired
    DataSource dataSource;

    @Autowired
    private CustomerRepository customerRepository;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        System.out.println("DATASOURCE = " + dataSource);

        // If you want to check the HikariDataSource settings
        //HikariDataSource newds = (HikariDataSource)dataSource;
        //System.out.println("DATASOURCE = " + newds.getMaximumPoolSize());

        if (args.length <= 0) {
            System.err.println("[Usage] java xxx.jar {insert name email | display}");
        } else {
            if (args[0].equalsIgnoreCase("insert")) {
                System.out.println("Add customer...");
                String name = args[1];
                String email = args[2];
                customerRepository.addCustomer(name, email);
            }

            if (args[0].equalsIgnoreCase("display")) {
                System.out.println("Display all customers...");
                List list = customerRepository.findAll();
                list.forEach(x -> System.out.println(x));
            }
            System.out.println("Done!");
        }
        exit(0);
    }
}

完了しました。

7. DEMO

ターミナル

$ mvn package

# 1. The database is initialized, the table is created, data is inserted
$ java -jar target/spring-boot-jdbc-1.0.jar

DATASOURCE = HikariDataSource (HikariPool-1)
[Usage] java xxx.jar {insert name email | display}

# 2. Disable database initialize process, and insert a new customer
$ java -Dspring.datasource.initialize=false -jar target/spring-boot-jdbc-1.0.jar insert newUser newPassword

DATASOURCE = HikariDataSource (null)
Add customer...
Done!

# 3. Display all customers
$ java -Dspring.datasource.initialize=false -jar target/spring-boot-jdbc-1.0.jar display
DATASOURCE = HikariDataSource (null)
Display all customers...
Customer{id=1, name='example', email='[email protected]', date=2017-02-11}
Customer{id=2, name='yflow', email='[email protected]', date=2017-02-12}
Customer{id=3, name='zilap', email='[email protected]', date=2017-02-13}
Customer{id=4, name='newUser', email='newPassword', date=2017-02-12}
Done!

ソースコードをダウンロード

ダウンロード–spring-boot-jdbc-example.zip(7 KB)