Пример базы данных Oracle Spring Boot JDBC Commons DBCP2

Spring Boot JDBC + база данных Oracle + пример Commons DBCP2

В этой статье мы покажем вам, как создать JDBC-приложение Spring Boot + база данных Oracle + пул соединений Commons DBCP2.

Инструменты, используемые в этой статье:

  1. Spring Boot 1.5.1.RELEASE

  2. База данных Oracle 11g экспресс

  3. Драйвер Oracle JDBC ojdbc7.jar

  4. Commons DBCP2 2.1.1

  5. специалист

  6. Java 8

1. Структура проекта

Стандартная структура проекта Maven.

image

2. Зависимость проекта

Download and Install Oracle JDBC driver.
Лицензионное ограничение Oracle, вы не можете получить драйвер Oracle JDBC из общедоступного репозитория Maven. Вместо этого вам нужно перейти на веб-сайт Oracle, чтобы загрузить драйвер иinstall into the Local Maven repository manually.

Объявляет Spring Boot JDBCspring-boot-starter-jdbc, драйвер Oracle JDBC (установить вручную)ojdbc7 и общий пул соединений DBCP2.

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 по умолчанию использует пул Tomcattomcat-jdbc, и следуйте этой последовательности, чтобы найти пул соединений:

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

Прочтите этот официальный документ Spring Boot -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 по умолчанию включает инициализатор источника данных и загружает сценарии 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.

image

Скачать исходный код

Скачать -spring-boot-jdbc-oracle-example.zip (7 КБ)

Related