Spring Boot JDBC + base de données Oracle + exemple Commons DBCP2
Dans cet article, nous allons vous montrer comment créer une application Spring Boot JDBC + une base de données Oracle + un pool de connexions Commons DBCP2.
Outils utilisés dans cet article:
-
Spring Boot 1.5.1.RELEASE
-
Base de données Oracle 11g express
-
Pilote JDBC Oracle ojdbc7.jar
-
Commons DBCP2 2.1.1
-
Maven
-
Java 8
Note
Associé -Spring Boot JDBC + MySQL + HikariCP example
1. Structure du projet
Une structure de projet Maven standard.
2. Dépendance du projet
Download and Install Oracle JDBC driver.
Restriction de licence Oracle, vous ne pouvez pas obtenir le pilote Oracle JDBC à partir du référentiel public Maven. Au lieu de cela, vous devez vous rendre sur le site Web d'Oracle pour télécharger le pilote etinstall into the Local Maven repository manually.
Déclare Spring Boot JDBCspring-boot-starter-jdbc
, Oracle JDBC Driver (installation manuelle)ojdbc7
et le pool de connexions Common 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
Terminal
$ 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 utilise le pool de Tomcattomcat-jdbc
par défaut, et suivez cette séquence pour trouver le pool de connexions:
Tomcat pool -->> - HikariCP -->> Commons DBCP -->> Commons DBCP2
Lisez ce document officiel de 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 ListfindAll() { 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. Initialisation de la base de données
Spring boot active l'initialiseur dataSource par défaut et charge les scripts SQL -schema.sql
etdata.sql
à partir de la racine du chemin de classe.
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
Lire ceci -Spring Database initialization
5. Configuration
Configurez Oracle etdbcp2 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
Application de ligne de commande 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..."); Listlist = customerRepository.findAll(); list.forEach(x -> System.out.println(x)); System.out.println("Done!"); exit(0); } }
7. DEMO
Exécutez-le, Spring Boot charge automatiquement les scriptsschema.sql
etdata.sql
et affiche le résultat.
Terminal
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!
Si vous définissez un point d'arrêt dans la session de débogage, consultez la page de session d'administration Web Oracle.
Télécharger le code source
Télécharger -spring-boot-jdbc-oracle-example.zip (7 KB)