最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring boot 使用JdbcTemplate訪問數(shù)據(jù)庫

 更新時間:2018年05月07日 15:10:49   作者:唐亞峰 | battcn  
SpringBoot 是為了簡化 Spring 應(yīng)用的創(chuàng)建、運行、調(diào)試、部署等一系列問題而誕生的產(chǎn)物。本文重點給大家介紹spring boot 使用JdbcTemplate訪問數(shù)據(jù)庫,需要的朋友可以參考下

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 的依賴

<!-- 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>
<!-- 默認就內(nèi)嵌了Tomcat 容器,如需要更換容器也極其簡單-->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

連接數(shù)據(jù)庫

在 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<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);
 }
}

測試

由于上面的接口是 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("[添加用戶成功]\n");
  // TODO 如果是返回的集合,要用 exchange 而不是 getForEntity ,后者需要自己強轉(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 常用的幾種操作,詳細請參考 JdbcTemplate API文檔

目前很多大佬都寫過關(guān)于 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE 編寫,包括新版本的特性都會一起介紹…

相關(guān)文章

  • springMVC利用FastJson接口返回json數(shù)據(jù)相關(guān)配置詳解

    springMVC利用FastJson接口返回json數(shù)據(jù)相關(guān)配置詳解

    本篇文章主要介紹了springMVC利用FastJson接口返回json數(shù)據(jù)相關(guān)配置詳解,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Java使用DateFormatter格式化日期時間的方法示例

    Java使用DateFormatter格式化日期時間的方法示例

    這篇文章主要介紹了Java使用DateFormatter格式化日期時間的方法,結(jié)合具體實例分析了java使用DateFormatter格式化日期時間的相關(guān)操作技巧,需要的朋友可以參考下
    2017-04-04
  • 使用mybatis框架連接mysql數(shù)據(jù)庫的超詳細步驟

    使用mybatis框架連接mysql數(shù)據(jù)庫的超詳細步驟

    MyBatis是目前java項目連接數(shù)據(jù)庫的最流行的orm框架了,下面這篇文章主要給大家介紹了關(guān)于使用mybatis框架連接mysql數(shù)據(jù)庫的超詳細步驟,文中通過實例代碼和圖文介紹的非常詳細,需要的朋友可以參考下
    2023-04-04
  • RocketMQ線程池創(chuàng)建實現(xiàn)原理詳解

    RocketMQ線程池創(chuàng)建實現(xiàn)原理詳解

    這篇文章主要為大家介紹了RocketMQ線程池創(chuàng)建實現(xiàn)原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12
  • Java設(shè)計模式中的原型模式講解

    Java設(shè)計模式中的原型模式講解

    原型模式是用于創(chuàng)建重復(fù)的對象,同時又能保證性能。這種類型的設(shè)計模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對象的最佳方式,今天通過本文給大家介紹下Java?原型設(shè)計模式,感興趣的朋友一起看看吧
    2023-04-04
  • 詳解SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型

    詳解SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型

    本文主要介紹了SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Mybatis中注解@MapKey的使用方式

    Mybatis中注解@MapKey的使用方式

    MyBatis使用@MapKey注解進行連表查詢,返回一個Map集合,Map的key為每條記錄的主鍵或指定字段,value為該記錄的字段名稱和字段值
    2024-12-12
  • 輕量級聲明式的Http庫——Feign的獨立使用

    輕量級聲明式的Http庫——Feign的獨立使用

    這篇文章主要介紹了輕量級聲明式的Http庫——Feign的使用教程,幫助大家更好的理解和學(xué)習(xí)使用feign,感興趣的朋友可以了解下
    2021-04-04
  • Javassist之一秒理解java動態(tài)編程

    Javassist之一秒理解java動態(tài)編程

    概述Javassist是一款字節(jié)碼編輯工具,可以直接編輯和生成Java生成的字節(jié)碼,以達到對.class文件進行動態(tài)修改的效果。
    2019-06-06
  • SpringBoot 中的異步處理機制詳解

    SpringBoot 中的異步處理機制詳解

    本文介紹了異步處理的基礎(chǔ)配置、線程池的自定義以及常見應(yīng)用場景,在實際應(yīng)用中,異步處理可以有效提升應(yīng)用的性能,改善用戶體驗,但同時也需要我們合理管理線程池,確保系統(tǒng)資源的高效利用,感興趣的朋友跟隨小編一起看看吧
    2025-01-01

最新評論

九龙坡区| 娄烦县| 闸北区| 临朐县| 墨江| 突泉县| 仙游县| 修文县| 高阳县| 福建省| 凌海市| 天祝| 陇川县| 泾源县| 西安市| 岐山县| 华蓥市| 肥西县| 吕梁市| 阿尔山市| 榆树市| 沙雅县| 神农架林区| 区。| 冕宁县| 昌黎县| 儋州市| 教育| 资兴市| 巴林右旗| 灵台县| 屯昌县| 云龙县| 黄梅县| 大埔县| 沈阳市| 武汉市| 镇远县| 吉隆县| 柳林县| 固镇县|