Spring boot 使用JdbcTemplate訪問(wèn)數(shù)據(jù)庫(kù)
SpringBoot 是為了簡(jiǎn)化 Spring 應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問(wèn)題而誕生的產(chǎn)物, 自動(dòng)裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個(gè) WEB 工程
Spring Framework 對(duì)數(shù)據(jù)庫(kù)的操作在 JDBC 上面做了深層次的封裝,通過(guò) 依賴注入 功能,可以將 DataSource 注冊(cè)到 JdbcTemplate 之中,使我們可以輕易的完成對(duì)象關(guān)系映射,并有助于規(guī)避常見(jiàn)的錯(cuò)誤,在 SpringBoot 中我們可以很輕松的使用它。
特點(diǎn)
- 速度快,對(duì)比其它的ORM框架而言,JDBC的方式無(wú)異于是最快的
- 配置簡(jiǎn)單, Spring 自家出品,幾乎沒(méi)有額外配置
- 學(xué)習(xí)成本低,畢竟 JDBC 是基礎(chǔ)知識(shí), JdbcTemplate 更像是一個(gè) DBUtils
導(dǎo)入依賴
在 pom.xml 中添加對(duì) JdbcTemplate 的依賴
<!-- Spring JDBC 的依賴包,使用 spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa 將會(huì)自動(dòng)獲得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> <!-- 默認(rèn)就內(nèi)嵌了Tomcat 容器,如需要更換容器也極其簡(jiǎn)單--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
連接數(shù)據(jù)庫(kù)
在 application.properties 中添加如下配置。值得注意的是,SpringBoot默認(rèn)會(huì)自動(dòng)配置 DataSource ,它將優(yōu)先采用 HikariCP 連接池,如果沒(méi)有該依賴的情況則選取 tomcat-jdbc ,如果前兩者都不可用最后選取 Commons DBCP2 。 通過(guò) 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 #更多細(xì)微的配置可以通過(guò)下列前綴進(jìn)行調(diào)整 #spring.datasource.hikari #spring.datasource.tomcat #spring.datasource.dbcp2
啟動(dòng)項(xiàng)目,通過(guò)日志,可以看到默認(rèn)情況下注入的是 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)
具體編碼
完成基本配置后,接下來(lái)進(jìn)行具體的編碼操作。 為了減少代碼量,就不寫(xiě) UserDao 、 UserService 之類的接口了,將直接在 Controller 中使用 JdbcTemplate 進(jìn)行訪問(wèn)數(shù)據(jù)庫(kù)操作,這點(diǎn)是不規(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='用戶表';
實(shí)體類
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<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) { // 根據(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); } }
測(cè)試
由于上面的接口是 restful 風(fēng)格的接口,添加和修改無(wú)法通過(guò)瀏覽器完成,所以需要我們自己編寫(xiě) junit 或者使用 postman 之類的工具。
創(chuàng)建單元測(cè)試 Chapter4ApplicationTests ,通過(guò) TestRestTemplate 模擬 GET 、 POST 、 PUT 、 DELETE 等請(qǐng)求操作
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 ,后者需要自己強(qiáng)轉(zhuǎn)類型 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("[刪除用戶成功]"); } }
總結(jié)
本章介紹了 JdbcTemplate 常用的幾種操作,詳細(xì)請(qǐng)參考 JdbcTemplate API文檔
目前很多大佬都寫(xiě)過(guò)關(guān)于 SpringBoot 的教程了,如有雷同,請(qǐng)多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE 編寫(xiě),包括新版本的特性都會(huì)一起介紹…
- Spring操作JdbcTemplate數(shù)據(jù)庫(kù)的方法學(xué)習(xí)
- spring學(xué)習(xí)JdbcTemplate數(shù)據(jù)庫(kù)事務(wù)管理
- Spring學(xué)習(xí)JdbcTemplate數(shù)據(jù)庫(kù)事務(wù)參數(shù)
- Spring框架JdbcTemplate數(shù)據(jù)庫(kù)事務(wù)管理完全注解方式
- SpringBoot使用JdbcTemplate訪問(wèn)操作數(shù)據(jù)庫(kù)基本用法
- SpringBoot使用JdbcTemplate操作數(shù)據(jù)庫(kù)
- springboot使用JdbcTemplate完成對(duì)數(shù)據(jù)庫(kù)的增刪改查功能
- Spring Boot中使用jdbctemplate 操作MYSQL數(shù)據(jù)庫(kù)實(shí)例
- Spring JdbcTemplate執(zhí)行數(shù)據(jù)庫(kù)操作詳解
相關(guān)文章
Java中的權(quán)限修飾符(protected)示例詳解
這篇文章主要給大家介紹了關(guān)于Java中權(quán)限修飾符(protected)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01淺談Servlet 實(shí)現(xiàn)網(wǎng)頁(yè)重定向的方法
本篇文章主要介紹了Servlet 實(shí)現(xiàn)重定向幾種方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08java實(shí)現(xiàn)小i機(jī)器人api接口調(diào)用示例
這篇文章主要介紹了java實(shí)現(xiàn)小i機(jī)器人api接口調(diào)用示例,需要的朋友可以參考下2014-04-04Java面試問(wèn)題知識(shí)點(diǎn)總結(jié)
本文主要介紹并且整理了Java面試知識(shí)點(diǎn)總結(jié),,有需要的小伙伴可以參考下2017-04-04spring基于注解配置實(shí)現(xiàn)事務(wù)控制操作
這篇文章主要介紹了spring基于注解配置實(shí)現(xiàn)事務(wù)控制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09