SpringブートJDBC + Oracleデータベース+ Commons DBCP2の例

Spring Boot JDBC + Oracleデータベース+ Commons DBCP2の例

この記事では、Spring Boot JDBCアプリケーション+ Oracleデータベース+ Commons DBCP2接続プールを作成する方法を示します。

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

  1. Spring Boot 1.5.1.RELEASE

  2. Oracle Database 11g Express

  3. Oracle JDBCドライバーojdbc7.jar

  4. コモンズDBCP2 2.1.1

  5. メーベン

  6. Java 8

1. プロジェクト構造

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

image

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

Download and Install Oracle JDBC driver.
Oracleライセンスの制限により、パブリックMavenリポジトリからOracleJDBCドライバーを取得できません。 代わりに、Oracle Webサイトにアクセスして、ドライバとinstall into the Local Maven repository manuallyをダウンロードする必要があります。

Spring Boot JDBCspring-boot-starter-jdbc、Oracle JDBC Driver(手動でインストール)ojdbc7、およびCommonDBCP2接続プールを宣言します。

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.oracle
            ojdbc7
            12.1.0
        

        
        
            org.apache.commons
            commons-dbcp2
            2.1.1
        

    

    
        
            
            
                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:slf4j-api:jar:1.7.22: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.oracle:ojdbc7:jar:12.1.0:compile
[INFO] \- org.apache.commons:commons-dbcp2:jar:2.1.1:compile
[INFO]    +- org.apache.commons:commons-pool2:jar:2.4.2:compile
[INFO]    \- commons-logging:commons-logging:jar:1.2:compile
[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, just inject it into your bean.

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.List;

@Repository
public class CustomerRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // thanks Java 8, look the custom RowMapper
    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;

    }

}

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 SQL script to create a customer table.

schema.sql

CREATE TABLE CUSTOMER(
ID NUMBER(10) NOT NULL,
NAME VARCHAR2(100) NOT NULL,
EMAIL VARCHAR2(100) NOT NULL,
CREATED_DATE DATE NOT NULL,
CONSTRAINT CUSTOMER_PK PRIMARY KEY (ID)
);

4.2 SQL script to insert 3 rows into the customer table.

data.sql

INSERT INTO "CUSTOMER" (ID, NAME, EMAIL, CREATED_DATE) VALUES(1, 'example','[email protected]', TO_DATE('2017-02-11', 'yyyy-mm-dd'));
INSERT INTO "CUSTOMER" (ID, NAME, EMAIL, CREATED_DATE) VALUES(2, 'yflow','[email protected]', TO_DATE('2017-02-12', 'yyyy-mm-dd'));
INSERT INTO "CUSTOMER" (ID, NAME, EMAIL, CREATED_DATE) VALUES(3, 'zilap','[email protected]', TO_DATE('2017-02-13', 'yyyy-mm-dd'));

Note
これを読む–Spring Database initialization

5. 設定

Oracleとdbcp2 settingsを構成します。

application.properties

spring.main.banner-mode=off

# Set true for first time db initialization.
spring.datasource.initialize=true

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=password
spring.datasource.driver-class-oracle.jdbc.driver.OracleDriver

# dbcp2 settings
# spring.datasource.dbcp2.*

spring.datasource.dbcp2.initial-size=7
spring.datasource.dbcp2.max-total=20
spring.datasource.dbcp2.pool-prepared-statements=true

6. @SpringBootApplication

Spring Bootコマンドラインアプリケーション

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
    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);

        /// Get dbcp2 datasource settings
        // BasicDataSource newds = (BasicDataSource) dataSource;
        // System.out.println("BasicDataSource = " + newds.getInitialSize());

        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

それを実行すると、Spring Bootはschema.sqlおよびdata.sqlスクリプトを自動的にロードし、結果を表示します。

ターミナル

DATASOURCE = org.apache.commons.dbcp2.BasicDataSource@4eb386df
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}
Done!

デバッグセッションでブレークポイントを設定した場合は、Oracle Web管理セッションページを確認してください。

image

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

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