Spring Boot如何使用JDBC獲取相關(guān)的數(shù)據(jù)詳解
什么是JDBC
Java Database Connectivity 是一種用于執(zhí)行SQL語(yǔ)句的Java API,與數(shù)據(jù)庫(kù)建立連接、發(fā)送 操作數(shù)據(jù)庫(kù)的語(yǔ)句并處理結(jié)果。
Spring Boot 使用 JDBC
增加依賴
修改pom.xml:將dependecies 修改為如下兩個(gè)
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies>
創(chuàng)建 Customer.java 類
package com.example.kane.Model; public class Customer { private long id; private String firstName, lastName; public Customer(long id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return String.format( "Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } // getters & setters omitted for brevity }
修改Application 類
package com.example.kane; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; import com.example.kane.Model.Customer; @SpringBootApplication //@EnableScheduling public class RestfulWebService1Application implements CommandLineRunner{ private static final Logger log = LoggerFactory.getLogger(RestfulWebService1Application.class); public static void main(String args[]) { SpringApplication.run(RestfulWebService1Application.class, args); } @Autowired JdbcTemplate jdbcTemplate; @Override public void run(String... strings) throws Exception { log.info("Creating tables"); jdbcTemplate.execute("DROP TABLE customers IF EXISTS"); jdbcTemplate.execute("CREATE TABLE customers(" + "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))"); // Split up the array of whole names into an array of first/last names List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream() .map(name -> name.split(" ")) .collect(Collectors.toList()); // Use a Java 8 stream to print out each tuple of the list splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1]))); // Uses JdbcTemplate's batchUpdate operation to bulk load data jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames); log.info("Querying for customer records where first_name = 'Josh':"); jdbcTemplate.query( "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" }, (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name")) ).forEach(customer -> log.info(customer.toString())); } }
運(yùn)行項(xiàng)目看結(jié)果
2019-03-01 14:19:52.078 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Creating tables
2019-03-01 14:19:52.086 INFO 7436 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-03-01 14:19:52.392 INFO 7436 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-03-01 14:19:52.429 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for John Woo
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Jeff Dean
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Josh Bloch
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Josh Long
2019-03-01 14:19:52.461 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Querying for customer records where first_name = 'Josh':
2019-03-01 14:19:52.480 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Customer[id=3, firstName='Josh', lastName='Bloch']
2019-03-01 14:19:52.480 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Customer[id=4, firstName='Josh', lastName='Long']
2019-03-01 14:20:01.122 INFO 7436 --- [nio-8080-exec-5] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-03-01 14:20:01.123 INFO 7436 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-03-01 14:20:01.146 INFO 7436 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed initialization in 22 ms
說明
官網(wǎng)的例子,沒有配置JDBC Template的Datasource,默認(rèn)使用的是H2 的內(nèi)存存儲(chǔ)的數(shù)據(jù)庫(kù),只能當(dāng)做測(cè)試使用。下面會(huì)有介紹更改DataSource的方法
介紹下 CommandLineRunner
功能
在項(xiàng)目啟動(dòng)后,執(zhí)行執(zhí)行功能,我們可以定一個(gè)類,去實(shí)現(xiàn)CommandLineRunner接口,重寫run方法,執(zhí)行一部分操作。需要注意的是,定義類必須標(biāo)記為Spring管理的組件
測(cè)試類
package com.example.kane.Model; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value=1) //因?yàn)榭赡苡性S多事情要做,Order 可以根據(jù)大小,判讀執(zhí)行的順序 public class run_after_application implements CommandLineRunner{ @Override public void run(String... args) throws Exception { // TODO Auto-generated method stub System.out.println("-----------------------"); } }
介紹下JdbcTempalte
在JDBC核心包中,JdbcTemplate是主要的類,簡(jiǎn)化了JDBC的使用,避免了一些常規(guī)錯(cuò)誤。它能夠執(zhí)行JDBC核心流程,在應(yīng)用代碼之上提供SQL語(yǔ)句、導(dǎo)出結(jié)果。這個(gè)類執(zhí)行SQL查詢、更新、對(duì)結(jié)果集重復(fù)操作捕獲JDBC的異常。并將它翻譯成org.springframework.dao 包中定義的基本的、信息量更大的異常層次結(jié)構(gòu)。
JDBC構(gòu)造方法
JdbcTemplate()
//為Bean創(chuàng)建一個(gè)JdbcTemplate以供使用 //再?zèng)]配置DataSource的情況下 springboot提供了 一些嵌入式的數(shù)據(jù)庫(kù)支持,上面的例子使用的就是H2數(shù)據(jù)庫(kù),是一個(gè)內(nèi)存的數(shù)據(jù)庫(kù)
JdbcTemplate(javax.sql.DataSource dataSource)
//構(gòu)造的時(shí)候傳入一個(gè) DataSource,來獲取鏈接 //JdbcTemplate Spring boot默認(rèn)鏈接的是H2 database,
在spring boot中配置mysql 數(shù)據(jù)庫(kù)
數(shù)據(jù)庫(kù)配置類 db_config
package com.example.kane.config; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class db_config { //這個(gè)類是一個(gè)Config類 @Value("${db.driver}") private String DRIVER; @Value("${db.password}") private String PASSWORD; @Value("${db.url}") private String URL; @Value("${db.username}") private String USERNAME; @Bean public DataSource dataSource1() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(DRIVER); dataSource.setUrl(URL); dataSource.setUsername(USERNAME); dataSource.setPassword(PASSWORD); return dataSource; } }
application.properties
# Database # mysqljdbc連接驅(qū)動(dòng) db.driver:com.mysql.cj.jdbc.Driver db.url:jdbc:mysql://localhost:3306/test db.username:root db.password:root
pom.xml
<dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 需要用到commons-dbcp連接池,以及連接mysql使用的drver-->
application 啟動(dòng)類修改
@Autowired JdbcTemplate jdbcTemplate; //下面是加載了數(shù)據(jù)庫(kù)的配置。只需要增加這個(gè) @Autowired db_config db_config;
運(yùn)行程序后會(huì)發(fā)現(xiàn)數(shù)據(jù)存儲(chǔ)到本地?cái)?shù)據(jù)庫(kù)
SELECT * from customers; ------------------------ 1 John Woo 2 Jeff Dean 3 Josh Bloch 4 Josh Long
另一個(gè)簡(jiǎn)單的方法配置mysql數(shù)據(jù)庫(kù)
直接修改application.properties
# database spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password= spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
將properties改成yml文件 application.yml
spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
注:這兩種方式又回歸到配置文件的方式了,
JDBC Template常用方法
- execute方法:可以用于執(zhí)行任何SQL語(yǔ)句,一般用于執(zhí)行DDL語(yǔ)句;
- update方法及batchUpdate方法:update方法用于執(zhí)行新增、修改、刪除等語(yǔ)句;batchUpdate方法用于執(zhí)行批處理相關(guān)語(yǔ)句;
- query方法及queryForXXX方法:用于執(zhí)行查詢相關(guān)語(yǔ)句;
- call方法:用于執(zhí)行存儲(chǔ)過程、函數(shù)相關(guān)語(yǔ)句。
- 參考官網(wǎng) https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html
關(guān)于連接池的一些內(nèi)容
為什么要使用數(shù)據(jù)庫(kù)連接池?
因?yàn)榻?shù)據(jù)庫(kù)連接是一個(gè)非常耗時(shí)的過程,使用連接池可以預(yù)先同數(shù)據(jù)庫(kù)建立連接,放在內(nèi)存中。應(yīng)用需要使用數(shù)據(jù)庫(kù)的時(shí)候直接使用連接池中的連接即可。
當(dāng)前三大主流連接池
- DBCP:提供最大空閑連接數(shù),超過連接全部自動(dòng)斷開連接,其他兩個(gè)沒有。
- C3P0:提供最大空閑連接時(shí)間,這樣可以做到自動(dòng)收回空閑連接的機(jī)制
- Druid:阿里出品的,同樣提供最大的空閑連接時(shí)間
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
使用spring boot開發(fā)時(shí)java對(duì)象和Json對(duì)象轉(zhuǎn)換的問題
這篇文章主要介紹了使用spring boot開發(fā)時(shí)java對(duì)象和Json對(duì)象轉(zhuǎn)換的問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03EL表達(dá)式簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
EL全名為Expression Language,這篇文章主要給大家介紹EL表達(dá)式的主要作用及內(nèi)容簡(jiǎn)介,感興趣的朋友一起看看2017-07-07Mybatis通過Mapper代理連接數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了Mybatis通過Mapper代理連接數(shù)據(jù)庫(kù)的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-11-11Java Swing JCheckBox復(fù)選框的實(shí)現(xiàn)方法
這篇文章主要介紹了Java Swing JCheckBox復(fù)選框的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Java數(shù)據(jù)敏感詞轉(zhuǎn)換成符號(hào)的方法詳解
在某個(gè)論壇下用戶可以隨意留言,為了防止不法分子在網(wǎng)上任意沖浪,需要對(duì)一些敏感詞匯進(jìn)行一些校驗(yàn),所以這篇文章給大家介紹了Java數(shù)據(jù)敏感詞轉(zhuǎn)換成符號(hào)的方法,需要的朋友可以參考下2024-03-03