原文鏈接:https://blog.csdn.net/wangmx1993328/article/details/81834974
目錄
環境准備
新建項目
pom. xml 默認內容
mysql 數據庫
數據庫 CRUD
全局配置文件
默認數據源
CRUD 數據庫
PhoneController
測試結果
自動配置原理
DataSourceConfiguration
1、《Spring Boot 數據庫訪問 簡介》中已經介紹,Spring Boot 可以通過多種方式訪問各種數據庫,本文將介紹 Spring Boot 內部集成的 JDBC 模板訪問 Mysql 數據庫
2、為了更加清晰明了,本文將新建項目進行說明。
環境准備
新建項目
pom. xml 默認內容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>www.wmx.com.horse</groupId>
<artifactId>horse</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>horse</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 引入Spring封裝的jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 引入html模板引擎Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 因為web項目啟動模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入mysql數據庫連接驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入Spring Boot 測試模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot 打包插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
mysql 數據庫
1、此 Mysql 數據是 CentOS 7.2 中的 Docker 容器中,所以用了 CentOS 的 3307 端口映射了 Docker 容器的 3306 端口,CentOS 主機 ip 為 192.168.58.129
2、賬號 root、密碼 root
數據庫 CRUD
全局配置文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.58.129:3307/horse?characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
1、配置的內容以及意義就如同以前在 Sping 核心配置文件 beans.xml 中配置時是一樣的
2、到這里就已經可以操作數據庫了,因為 Spring Boot 都已經自動配置好了,如 Spring Boot 默認已經提供了數據源
3、關於上面的數據源配置內容,都可以從 Spring Boot 官方文檔 查看
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.continue-on-error=false # Whether to stop if an error occurs while initializing the database.
spring.datasource.data= # Data (DML) script resource references.
spring.datasource.data-username= # Username of the database to execute DML scripts (if different).
spring.datasource.data-password= # Password of the database to execute DML scripts (if different).
spring.datasource.dbcp2.*= # Commons DBCP2 specific settings
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.generate-unique-name=false # Whether to generate a random datasource name.
spring.datasource.hikari.*= # Hikari specific settings
spring.datasource.initialization-mode=embedded # Initialize the datasource with available DDL and DML scripts.
spring.datasource.jmx-enabled=false # Whether to enable JMX support (if provided by the underlying pool).
spring.datasource.jndi-name= # JNDI location of the datasource. Class, url, username & password are ignored when set.
spring.datasource.name= # Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password= # Login password of the database.
spring.datasource.platform=all # Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or data-${platform}.sql).
spring.datasource.schema= # Schema (DDL) script resource references.
spring.datasource.schema-username= # Username of the database to execute DDL scripts (if different).
spring.datasource.schema-password= # Password of the database to execute DDL scripts (if different).
spring.datasource.separator=; # Statement separator in SQL initialization scripts.
spring.datasource.sql-script-encoding= # SQL scripts encoding.
spring.datasource.tomcat.*= # Tomcat datasource specific settings
spring.datasource.type= # Fully qualified name of the connection pool implementation to use. By default, it is auto-detected from the classpath.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.
spring.datasource.xa.data-source-class-name= # XA datasource fully qualified name.
spring.datasource.xa.properties= # Properties to pass to the XA data source.
4、也可以從 org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 數據源配置文件類中進行查看
默認數據源
1、全局配置文件 application.yml 中 spring.datasource 下只配置了賬號、密碼、數據庫地址、連接驅動,因為默認使用的是 class com.zaxxer.hikari.HikariDataSource 數據源
2、如果過是自定義數據源,比如 DruidDataSource,則可以使用 type 指定,如下所示:
type: com.alibaba.druid.pool.DruidDataSource,可以參考《切換 Druid 數據源》
package com.lct.www;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HorseApplicationTests {
/**
* Spring Boot 默認已經配置好了數據源,程序員可以直接 DI 注入然后使用即可
*/
@Resource
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
System.out.println("數據源>>>>>>" + dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println("連接>>>>>>>>>" + connection);
System.out.println("連接地址>>>>>" + connection.getMetaData().getURL());
connection.close();
}
}
1、運行之后控制台核心輸出如下:
數據源>>>>>>class com.zaxxer.hikari.HikariDataSource
2018-08-19 09:31:31.689 INFO 8948 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2018-08-19 09:31:31.986 INFO 8948 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
連接>>>>>>>>>HikariProxyConnection@280862192 wrapping com.mysql.jdbc.JDBC4Connection@3ae0b770
連接地址>>>>>jdbc:mysql://192.168.58.129:3307/horse
2018-08-19 09:31:31.996 INFO 8948 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@dc7df28: startup date [Sun Aug 19 09:31:29 CST 2018]; root of context hierarchy
2018-08-19 09:31:31.998 INFO 8948 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2018-08-19 09:31:32.001 INFO 8948 --- [ Thread-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
1、可以看出 Spring Boot 2.0.4 默認使用 com.zaxxer.hikari.HikariDataSource 數據源,而以前版本,如 Spring Boot 1.5 默認使用 org.apache.tomcat.jdbc.pool.DataSource 作為數據源;
2、HikariDataSource 號稱 Java WEB 當前速度最快的數據源,相比於傳統的 C3P0 、DBCP、Tomcat jdbc 等連接池更加優秀;
3、HikariDataSource 的內容本文暫時不做延伸,有了數據庫連接,顯然就可以 CRUD 操作數據庫了。
CRUD 數據庫
1、有了數據源(com.zaxxer.hikari.HikariDataSource),然后拿到l了數據庫連接(java.sql.Connection),自然就可以使用連接和原生的 JDCB 語句來操作數據庫
2、即使不使用第三方第數據庫操作框架,如 MyBatis、Hibernate 、JDBC Utils 等,Spring 本身也對 原生的 JDBC 做了輕量級的封裝,即 org.springframework.jdbc.core.JdbcTemplate。這原本是 Spring 的知識點!
3、數據庫操作的所有 CRUD 方法都在 JdbcTemplate 中,有了 JdbcTemplate 就能更加輕松的操作數據庫。
4、Spring Boot 不僅提供了默認的數據源,同時默認已經配置好了 JdbcTemplate 放在了容器中,程序員只需自己注入即可使用
5、JdbcTemplate 的自動配置原理是依賴 org.springframework.boot.autoconfigure.jdbc 包下的 org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration 類
PhoneController
1、為了盡可能符合實際開發,新建一個控制層,通過瀏覽器訪問來進行 CRUD,但是不再進行細致的分層,如 dao、service、domain 等都省略
package com.lct.www.controller;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2018/8/19 0019.
*/
@Controller
public class PhoneController {
/**
* JdbcTemplate 是 core 包的核心類,用於簡化 JDBC 操作,還能避免一些常見的錯誤,如忘記關閉數據庫連接
* Spring Boot 默認提供了數據源,默認提供了 org.springframework.jdbc.core.JdbcTemplate
* JdbcTemplate 中會自己注入數據源,使用起來也不用再自己來關閉數據庫連接
*/
@Resource
JdbcTemplate jdbcTemplate;
/**
* 查詢 phone 表所有數據
*
* @return
*/
@ResponseBody
@GetMapping("phoneList")
public List<Map<String, Object>> userList() {
/**
* 查詢 phone 表所有數據
* List 中的1個 Map 對應數據庫的 1行數據
* Map 中的 key 對應數據庫的字段名,value 對應數據庫的字段值
*/
List<Map<String, Object>> mapList = jdbcTemplate.queryForList("SELECT * FROM phone");
return mapList;
}
/**
* 新增 phone 數據
*
* @return
*/
@GetMapping("savePhone")
public String savePhone() {
String sql = "INSERT INTO phone(number,region) VALUES (?,?)";
Object[] objects = new Object[2];
objects[0] = "18673886425";
objects[1] = "湖南";
jdbcTemplate.update(sql, objects);
return "forward:/phoneList";
}
/**
* 修改 phone 數據
*
* @return
*/
@GetMapping("updatePhone")
public String updatePhone() {
String sql = "UPDATE phone SET number=? WHERE pid=?";
Object[] objects = new Object[2];
objects[0] = "18666668888";
objects[1] = "1";
jdbcTemplate.update(sql, objects);
return "forward:/phoneList";
}
/**
* 刪除 phone 數據
* update 方法可以做查詢以外的 增加、修改、刪除操作
*
* @return
*/
@GetMapping("deletePhone")
public String deletePhone() {
String sql = "DELETE FROM phone WHERE number=?";
Object[] objects = new Object[1];
objects[0] = "18673886425";
jdbcTemplate.update(sql, objects);
return "forward:/phoneList";
}
}
測試結果
1、啟動應用成功
some templates or check your Thymeleaf configuration)
2018-08-19 12:15:23.522 INFO 14052 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-08-19 12:15:23.525 INFO 14052 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-19 12:15:23.532 INFO 14052 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-19 12:15:23.573 INFO 14052 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-08-19 12:15:23.577 INFO 14052 --- [ main] com.lct.www.HorseApplication : Started HorseApplication in 3.863 seconds (JVM running for 4.455)
2、瀏覽器訪問測試
查詢:http://localhost:8080/phoneList
添加:http://localhost:8080/savePhone
修改:http://localhost:8080/updatePhone
刪除:http://localhost:8080/deletePhone
自動配置原理
1、自動配置都在 org.springframework.boot.autoconfigure.jdbc 包下可以找到
DataSourceConfiguration
1、org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration 數據源配置類作用是根據邏輯判斷之后,添加數據源
2、SpringBoot 默認支持如下數據源;
com.zaxxer.hikari.HikariDataSource (Spring Boot 2.0 以上,默認使用此數據源)
org.apache.tomcat.jdbc.pool.DataSource
org.apache.commons.dbcp2.BasicDataSource
3、可以使用 spring.datasource.type 指定自定義的數據源類型,值為 要使用的連接池實現的完全限定名。默認情況下,它是從類路徑自動檢測的。
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
@Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}
}
————————————————
版權聲明:本文為CSDN博主「蚩尤后裔」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/wangmx1993328/article/details/81834974