什么是jdbc
java database connectivity 是一種用于執(zhí)行sql語句的java api,與數(shù)據(jù)庫建立連接、發(fā)送 操作數(shù)據(jù)庫的語句并處理結(jié)果。
spring boot 使用 jdbc
增加依賴
修改pom.xml:將dependecies 修改為如下兩個
1
2
3
4
5
6
7
8
9
10
|
<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 類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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 類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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)行項目看結(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)存存儲的數(shù)據(jù)庫,只能當(dāng)做測試使用。下面會有介紹更改datasource的方法
介紹下 commandlinerunner
功能
在項目啟動后,執(zhí)行執(zhí)行功能,我們可以定一個類,去實現(xiàn)commandlinerunner接口,重寫run方法,執(zhí)行一部分操作。 需要注意的是,定義類必須標(biāo)記為spring管理的組件
測試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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 ) //因為可能有許多事情要做,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是主要的類,簡化了jdbc的使用,避免了一些常規(guī)錯誤。它能夠執(zhí)行jdbc核心流程,在應(yīng)用代碼之上提供sql語句、導(dǎo)出結(jié)果。這個類執(zhí)行sql查詢、更新、對結(jié)果集重復(fù)操作捕獲jdbc的異常。并將它翻譯成 org.springframework.dao
包中定義的基本的、信息量更大的異常層次結(jié)構(gòu)。
jdbc構(gòu)造方法
jdbctemplate()
1
2
|
//為bean創(chuàng)建一個jdbctemplate以供使用 //再沒配置datasource的情況下 springboot提供了 一些嵌入式的數(shù)據(jù)庫支持,上面的例子使用的就是h2數(shù)據(jù)庫,是一個內(nèi)存的數(shù)據(jù)庫 |
jdbctemplate(javax.sql.datasource datasource)
1
2
|
//構(gòu)造的時候傳入一個 datasource,來獲取鏈接 //jdbctemplate spring boot默認(rèn)鏈接的是h2 database, |
在spring boot中配置mysql 數(shù)據(jù)庫
數(shù)據(jù)庫配置類 db_config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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 { //這個類是一個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
1
2
3
4
5
6
|
# database # mysqljdbc連接驅(qū)動 db.driver:com.mysql.cj.jdbc.driver db.url:jdbc:mysql: //localhost:3306/test db.username:root db.password:root |
pom.xml
1
2
3
4
5
6
7
8
9
10
11
|
<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 啟動類修改
1
2
3
4
5
|
@autowired jdbctemplate jdbctemplate; //下面是加載了數(shù)據(jù)庫的配置。只需要增加這個 @autowired db_config db_config; |
運(yùn)行程序后會發(fā)現(xiàn)數(shù)據(jù)存儲到本地數(shù)據(jù)庫
1
2
3
4
5
6
|
select * from customers; ------------------------ 1 john woo 2 jeff dean 3 josh bloch 4 josh long |
另一個簡單的方法配置mysql數(shù)據(jù)庫
直接修改application.properties
1
2
3
4
5
|
# 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
1
2
3
4
5
6
|
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語句,一般用于執(zhí)行ddl語句;
- update方法及batchupdate方法: update方法用于執(zhí)行新增、修改、刪除等語句;batchupdate方法用于執(zhí)行批處理相關(guān)語句;
- query方法及queryforxxx方法: 用于執(zhí)行查詢相關(guān)語句;
- call方法: 用于執(zhí)行存儲過程、函數(shù)相關(guān)語句。
關(guān)于連接池的一些內(nèi)容
為什么要使用數(shù)據(jù)庫連接池?
因為建立數(shù)據(jù)庫連接是一個非常耗時的過程,使用連接池可以預(yù)先同數(shù)據(jù)庫建立連接,放在內(nèi)存中。應(yīng)用需要使用數(shù)據(jù)庫的時候直接使用連接池中的連接即可。
當(dāng)前三大主流連接池
- dbcp:提供最大空閑連接數(shù),超過連接全部自動斷開連接,其他兩個沒有。
- c3p0:提供最大空閑連接時間,這樣可以做到自動收回空閑連接的機(jī)制
- druid:阿里出品的,同樣提供最大的空閑連接時間
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/primadonna/p/10470472.html