springboot 是為了簡化 spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物, 自動裝配的特性讓我們可以更好的關注業務本身而不是外部的xml配置,我們只需遵循規范,引入相關的依賴就可以輕易的搭建出一個 web 工程
spring framework 對數據庫的操作在 jdbc 上面做了深層次的封裝,通過 依賴注入 功能,可以將 datasource 注冊到 jdbctemplate 之中,使我們可以輕易的完成對象關系映射,并有助于規避常見的錯誤,在 springboot 中我們可以很輕松的使用它。
特點
- 速度快,對比其它的orm框架而言,jdbc的方式無異于是最快的
- 配置簡單, spring 自家出品,幾乎沒有額外配置
- 學習成本低,畢竟 jdbc 是基礎知識, jdbctemplate 更像是一個 dbutils
導入依賴
在 pom.xml 中添加對 jdbctemplate 的依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!-- spring jdbc 的依賴包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 將會自動獲得hikaricp依賴 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-jdbc</artifactid> </dependency> <!-- mysql包 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> </dependency> <!-- 默認就內嵌了tomcat 容器,如需要更換容器也極其簡單--> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> |
連接數據庫
在 application.properties 中添加如下配置。值得注意的是,springboot默認會自動配置 datasource ,它將優先采用 hikaricp 連接池,如果沒有該依賴的情況則選取 tomcat-jdbc ,如果前兩者都不可用最后選取 commons dbcp2 。 通過 spring.datasource.type 屬性可以指定其它種類的連接池
1
2
3
4
5
6
7
8
|
spring.datasource.url=jdbc:mysql: //localhost:3306/chapter4?useunicode=true&characterencoding=utf-8&zerodatetimebehavior=converttonull&allowmultiqueries=true&usessl=false spring.datasource.password=root spring.datasource.username=root #spring.datasource.type #更多細微的配置可以通過下列前綴進行調整 #spring.datasource.hikari #spring.datasource.tomcat #spring.datasource.dbcp2 |
啟動項目,通過日志,可以看到默認情況下注入的是 hikaridatasource
1
2
3
4
|
2018 - 05 - 07 10 : 33 : 54.021 info 9640 --- [ main] o.s.j.e.a.annotationmbeanexporter : bean with name 'datasource' has been autodetected for jmx exposure 2018 - 05 - 07 10 : 33 : 54.026 info 9640 --- [ main] o.s.j.e.a.annotationmbeanexporter : located mbean 'datasource' : registering with jmx server as mbean [com.zaxxer.hikari:name=datasource,type=hikaridatasource] 2018 - 05 - 07 10 : 33 : 54.071 info 9640 --- [ main] o.s.b.w.embedded.tomcat.tomcatwebserver : tomcat started on port(s): 8080 (http) with context path '' 2018 - 05 - 07 10 : 33 : 54.075 info 9640 --- [ main] com.battcn.chapter4application : started chapter4application in 3.402 seconds (jvm running for 3.93 ) |
具體編碼
完成基本配置后,接下來進行具體的編碼操作。 為了減少代碼量,就不寫 userdao 、 userservice 之類的接口了,將直接在 controller 中使用 jdbctemplate 進行訪問數據庫操作,這點是不規范的,各位別學我…
表結構
創建一張 t_user 的表
1
2
3
4
5
6
|
create table `t_user` ( `id` int ( 8 ) not null auto_increment comment '主鍵自增' , `username` varchar( 50 ) not null comment '用戶名' , `password` varchar( 50 ) not null comment '密碼' , primary key (`id`) ) engine=innodb default charset=utf8 comment= '用戶表' ; |
實體類
1
2
3
4
5
6
7
8
9
10
11
12
|
package com.battcn.entity; /** * @author levin * @since 2018/5/7 0007 */ public class user { private long id; private string username; private string password; // todo 省略get set } |
restful 風格接口
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
|
package com.battcn.controller; import com.battcn.entity.user; import org.springframework.beans.factory.annotation.autowired; import org.springframework.jdbc.core.beanpropertyrowmapper; import org.springframework.jdbc.core.jdbctemplate; import org.springframework.web.bind.annotation.*; import java.util.list; /** * @author levin * @since 2018/4/23 0023 */ @restcontroller @requestmapping ( "/users" ) public class springjdbccontroller { private final jdbctemplate jdbctemplate; @autowired public springjdbccontroller(jdbctemplate jdbctemplate) { this .jdbctemplate = jdbctemplate; } @getmapping public list<user> queryusers() { // 查詢所有用戶 string sql = "select * from t_user" ; return jdbctemplate.query(sql, new object[]{}, new beanpropertyrowmapper<>(user. class )); } @getmapping ( "/{id}" ) public user getuser( @pathvariable long id) { // 根據主鍵id查詢 string sql = "select * from t_user where id = ?" ; return jdbctemplate.queryforobject(sql, new object[]{id}, new beanpropertyrowmapper<>(user. class )); } @deletemapping ( "/{id}" ) public int deluser( @pathvariable long id) { // 根據主鍵id刪除用戶信息 string sql = "delete from t_user where id = ?" ; return jdbctemplate.update(sql, id); } @postmapping public int adduser( @requestbody user user) { // 添加用戶 string sql = "insert into t_user(username, password) values(?, ?)" ; return jdbctemplate.update(sql, user.getusername(), user.getpassword()); } @putmapping ( "/{id}" ) public int edituser( @pathvariable long id, @requestbody user user) { // 根據主鍵id修改用戶信息 string sql = "update t_user set username = ? ,password = ? where id = ?" ; return jdbctemplate.update(sql, user.getusername(), user.getpassword(), id); } } |
測試
由于上面的接口是 restful 風格的接口,添加和修改無法通過瀏覽器完成,所以需要我們自己編寫 junit 或者使用 postman 之類的工具。
創建單元測試 chapter4applicationtests ,通過 testresttemplate 模擬 get 、 post 、 put 、 delete 等請求操作
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
|
package com.battcn; import com.battcn.entity.user; import org.junit.test; import org.junit.runner.runwith; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; import org.springframework.boot.test.web.client.testresttemplate; import org.springframework.boot.web.server.localserverport; import org.springframework.core.parameterizedtypereference; import org.springframework.http.httpmethod; import org.springframework.http.responseentity; import org.springframework.test.context.junit4.springrunner; import java.util.list; /** * @author levin */ @runwith (springrunner. class ) @springboottest (classes = chapter4application. class , webenvironment = springboottest.webenvironment.random_port) public class chapter4applicationtests { private static final logger log = loggerfactory.getlogger(chapter4applicationtests. class ); @autowired private testresttemplate template; @localserverport private int port; @test public void test1() throws exception { template.postforentity( "http://localhost:" + port + "/users" , new user( "user1" , "pass1" ), integer. class ); log.info( "[添加用戶成功]\n" ); // todo 如果是返回的集合,要用 exchange 而不是 getforentity ,后者需要自己強轉類型 responseentity<list<user>> response2 = template.exchange( "http://localhost:" + port + "/users" , httpmethod.get, null , new parameterizedtypereference<list<user>>() { }); final list<user> body = response2.getbody(); log.info( "[查詢所有] - [{}]\n" , body); long userid = body.get( 0 ).getid(); responseentity<user> response3 = template.getforentity( "http://localhost:" + port + "/users/{id}" , user. class , userid); log.info( "[主鍵查詢] - [{}]\n" , response3.getbody()); template.put( "http://localhost:" + port + "/users/{id}" , new user( "user11" , "pass11" ), userid); log.info( "[修改用戶成功]\n" ); template.delete( "http://localhost:" + port + "/users/{id}" , userid); log.info( "[刪除用戶成功]" ); } } |
總結
本章介紹了 jdbctemplate 常用的幾種操作,詳細請參考 jdbctemplate api文檔
目前很多大佬都寫過關于 springboot 的教程了,如有雷同,請多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.release 編寫,包括新版本的特性都會一起介紹…
原文鏈接:http://blog.battcn.com/2018/05/07/springboot/v2-orm-jdbc