摘要:值得注意的是,默認會自動配置,它將優(yōu)先采用連接池,如果沒有該依賴的情況則選取,如果前兩者都不可用最后選取。
SpringBoot 是為了簡化 Spring 應(yīng)用的創(chuàng)建、運行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物,自動裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個 WEB 工程
Spring Framework對數(shù)據(jù)庫的操作在JDBC上面做了深層次的封裝,通過依賴注入功能,可以將 DataSource 注冊到JdbcTemplate之中,使我們可以輕易的完成對象關(guān)系映射,并有助于規(guī)避常見的錯誤,在SpringBoot中我們可以很輕松的使用它。
特點
速度快,對比其它的ORM框架而言,JDBC的方式無異于是最快的
配置簡單,Spring自家出品,幾乎沒有額外配置
學(xué)習(xí)成本低,畢竟JDBC是基礎(chǔ)知識,JdbcTemplate更像是一個DBUtils
導(dǎo)入依賴在 pom.xml 中添加對 JdbcTemplate 的依賴
連接數(shù)據(jù)庫org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java org.springframework.boot spring-boot-starter-web
在application.properties中添加如下配置。值得注意的是,SpringBoot默認會自動配置DataSource,它將優(yōu)先采用HikariCP連接池,如果沒有該依賴的情況則選取tomcat-jdbc,如果前兩者都不可用最后選取Commons DBCP2。通過spring.datasource.type屬性可以指定其它種類的連接池
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 #更多細微的配置可以通過下列前綴進行調(diào)整 #spring.datasource.hikari #spring.datasource.tomcat #spring.datasource.dbcp2
啟動項目,通過日志,可以看到默認情況下注入的是HikariDataSource
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進行訪問數(shù)據(jù)庫操作,這點是不規(guī)范的,各位別學(xué)我...
表結(jié)構(gòu)創(chuàng)建一張 t_user 的表
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="用戶表";實體類
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 風(fēng)格接口
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測試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) { // 根據(jù)主鍵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) { // 根據(jù)主鍵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) { // 根據(jù)主鍵ID修改用戶信息 String sql = "UPDATE t_user SET username = ? ,password = ? WHERE id = ?"; return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id); } }
由于上面的接口是 restful 風(fēng)格的接口,添加和修改無法通過瀏覽器完成,所以需要我們自己編寫junit或者使用postman之類的工具。
創(chuàng)建單元測試Chapter4ApplicationTests,通過TestRestTemplate模擬GET、POST、PUT、DELETE等請求操作
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("[添加用戶成功] "); // TODO 如果是返回的集合,要用 exchange 而不是 getForEntity ,后者需要自己強轉(zhuǎn)類型 ResponseEntity總結(jié)> response2 = template.exchange("http://localhost:" + port + "/users", HttpMethod.GET, null, new ParameterizedTypeReference
>() { }); final List
body = response2.getBody(); log.info("[查詢所有] - [{}] ", body); Long userId = body.get(0).getId(); ResponseEntity response3 = template.getForEntity("http://localhost:" + port + "/users/{id}", User.class, userId); log.info("[主鍵查詢] - [{}] ", response3.getBody()); template.put("http://localhost:" + port + "/users/{id}", new User("user11", "pass11"), userId); log.info("[修改用戶成功] "); template.delete("http://localhost:" + port + "/users/{id}", userId); log.info("[刪除用戶成功]"); } }
本章介紹了JdbcTemplate常用的幾種操作,詳細請參考JdbcTemplate API文檔
目前很多大佬都寫過關(guān)于 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE編寫,包括新版本的特性都會一起介紹...
說點什么個人QQ:1837307557
battcn開源群(適合新手):391619659
微信公眾號(歡迎調(diào)戲):battcn
個人博客:http://blog.battcn.com/
全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter4
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/71364.html
摘要:整合階段由于沒有對的快速啟動裝配,所以需要我自己導(dǎo)入相關(guān)的,包括數(shù)據(jù)源,包掃描,事物管理器等。另外它的中文文檔比較友好。源碼下載參考資料中文文檔 BeetSql是一個全功能DAO工具, 同時具有Hibernate 優(yōu)點 & Mybatis優(yōu)點功能,適用于承認以SQL為中心,同時又需求工具能自動能生成大量常用的SQL的應(yīng)用。 beatlsql 優(yōu)點 開發(fā)效率 無需注解,自動使用大...
摘要:忽略該字段的映射省略創(chuàng)建數(shù)據(jù)訪問層接口,需要繼承,第一個泛型參數(shù)是實體對象的名稱,第二個是主鍵類型。 SpringBoot 是為了簡化 Spring 應(yīng)用的創(chuàng)建、運行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物,自動裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個 WEB 工程 上一篇介紹了Spring JdbcTempl...
摘要:標(biāo)簽在為一個地址附加參數(shù)時,將自動對參數(shù)值進行編碼,例如,如果傳遞的參數(shù)值為中國,則將其轉(zhuǎn)換為后再附加到地址后面,這也就是使用標(biāo)簽的最大好處。 什么是JSTL JSTL全稱為 JSP Standard Tag Library 即JSP標(biāo)準(zhǔn)標(biāo)簽庫。 JSTL作為最基本的標(biāo)簽庫,提供了一系列的JSP標(biāo)簽,實現(xiàn)了基本的功能:集合的遍歷、數(shù)據(jù)的輸出、字符串的處理、數(shù)據(jù)的格式化等等! 為什么要使...
摘要:微信公眾號一個優(yōu)秀的廢人如有問題或建議,請后臺留言,我會盡力解決你的問題。前言如題,今天介紹通過訪問關(guān)系型通過的去訪問。我這里已經(jīng)全部測試通過,請放心使用。源碼下載后語以上用訪問的教程。另外,關(guān)注之后在發(fā)送可領(lǐng)取免費學(xué)習(xí)資料。 微信公眾號:一個優(yōu)秀的廢人如有問題或建議,請后臺留言,我會盡力解決你的問題。 前言 如題,今天介紹 springboot 通過jdbc訪問關(guān)系型mysql,通過...
閱讀 1911·2021-08-19 11:12
閱讀 1479·2021-07-25 21:37
閱讀 1036·2019-08-30 14:07
閱讀 1333·2019-08-30 13:12
閱讀 716·2019-08-30 11:00
閱讀 3590·2019-08-29 16:28
閱讀 1053·2019-08-29 15:33
閱讀 3022·2019-08-26 13:40