溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring Boot中如何使用JDBC

發(fā)布時(shí)間:2021-09-10 12:59:26 來(lái)源:億速云 閱讀:224 作者:chen 欄目:大數(shù)據(jù)

本篇內(nèi)容主要講解“Spring Boot中如何使用JDBC”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“Spring Boot中如何使用JDBC”吧!

閱讀目錄

一、JDBC是什么?

二、Spring Boot中如何使用JDBC

三、自動(dòng)配置原理

四、JdbcTemplate

五、配置Swagger用來(lái)測(cè)試

六、測(cè)試

七、報(bào)錯(cuò)和解決方案:

Github代碼下載:

     https://github.com/Jackson0714/study-spring-boot

一、JDBC是什么?

JDBC API 屬于Java APIJDBC用于以下幾種功能:連接到數(shù)據(jù)庫(kù)、執(zhí)行SQL語(yǔ)句

二、Spring Boot中如何使用JDBC

2.1 創(chuàng)建 Spring Boot Project 時(shí)引入 JDBC API 依賴和 MySQL Driver依賴,以及Spring Web依賴(測(cè)試時(shí)用到)

Spring Boot中如何使用JDBC
可以在POM中找到引入的JDBC依賴和mysql依賴:
JDBC 依賴:

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

MySql 驅(qū)動(dòng)依賴:

<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <scope>runtime</scope>
</dependency>

2.2 配置數(shù)據(jù)庫(kù)連接

新增配置文件:src/main/resources/application.yml

spring:
 datasource:
   username: root
   password: root
   url: jdbc:mysql://localhost:3306/study-spring-boot?serverTimezone=UTC&useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
   driverClassName: com.mysql.cj.jdbc.Driver

注意:com.mysq.jdbc.Driver 被廢棄了,需要使用com.mysql.cj.jdbc.Driver

2.3 查看使用的數(shù)據(jù)源和數(shù)據(jù)庫(kù)連接

package com.jackson0714.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


@SpringBootTest
class Springboot05DataJdbcApplicationTests {

   @Autowired
   DataSource dataSource; //自動(dòng)配置數(shù)據(jù)源,使用yml配置

   @Test
   void contextLoads() throws SQLException {
       System.out.println("數(shù)據(jù)源:" + dataSource.getClass());

       Connection connection = dataSource.getConnection();
       System.out.println("數(shù)據(jù)庫(kù)連接:" + connection);
       connection.close();
   }

}

默認(rèn)數(shù)據(jù)源:class com.zaxxer.hikari.HikariDataSource

數(shù)據(jù)庫(kù)連接:HikariProxyConnection@1335157064 wrapping com.mysql.cj.jdbc.ConnectionImpl@7ff8a9dc

Spring Boot中如何使用JDBC

三、自動(dòng)配置原理

自動(dòng)配置文件路徑:org.springframework.boot.autoconfigure.jdbc

DataSourceConfiguration用來(lái)自動(dòng)導(dǎo)入數(shù)據(jù)源(根據(jù)各種判斷)

/**
    * Tomcat Pool DataSource configuration.
    */
   @Configuration(proxyBeanMethods = false)
   @ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)
   @ConditionalOnMissingBean(DataSource.class)
   @ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource",
           matchIfMissing = true)
   static class Tomcat {

       @Bean
       @ConfigurationProperties(prefix = "spring.datasource.tomcat")

3.1 自動(dòng)選擇數(shù)據(jù)源

如果導(dǎo)入了org.apache.tomcat.jdbc.pool.DataSource數(shù)據(jù)源,并且配置的spring.datasource.type配置的是org.apache.tomcat.jdbc.pool.DataSource,或沒(méi)配置type也使用tomcat數(shù)據(jù)源

3.2 HikariDataSource數(shù)據(jù)源也類似這樣判斷。

3.3 默認(rèn)使用tomcat數(shù)據(jù)源

3.4 默認(rèn)支持以下數(shù)據(jù)源

org.apache.tomcat.jdbc.pool、HikariDataSource、org.apache.commons.dbcp2

3.5 支持自定義數(shù)據(jù)源

使用DataSourceBuilder創(chuàng)建數(shù)據(jù)源,利用反射創(chuàng)建響應(yīng)type的數(shù)據(jù)源,并且綁定相關(guān)屬性

    /**
    * Generic DataSource configuration.
    */
   @Configuration(proxyBeanMethods = false)
   @ConditionalOnMissingBean(DataSource.class)
   @ConditionalOnProperty(name = "spring.datasource.type")
   static class Generic {

       @Bean
       DataSource dataSource(DataSourceProperties properties) {
         //使用DataSourceBuilder創(chuàng)建數(shù)據(jù)源,利用反射創(chuàng)建響應(yīng)type的數(shù)據(jù)源,并且綁定相關(guān)屬性
           return properties.initializeDataSourceBuilder().build();
       }

   }

3.6 DataSourceInitializerInvoker 運(yùn)行腳本

/**
* Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on
* {@link InitializingBean#afterPropertiesSet()} and {@literal data-*.sql} SQL scripts on
* a {@link DataSourceSchemaCreatedEvent}.
*
* @author Stephane Nicoll
* @see DataSourceAutoConfiguration
*/
class DataSourceInitializerInvoker implements ApplicationListener<DataSourceSchemaCreatedEvent>, InitializingBean {
createSchema() 創(chuàng)建表 (文件名規(guī)則 schema-*.sql)
initSchema() 執(zhí)行數(shù)據(jù)腳本 (文件名規(guī)則 data-*.sql)

getScripts() 來(lái)獲取需要執(zhí)行的腳本

private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
 if (resources != null) {
   return getResources(propertyName, resources, true);
 }
 String platform = this.properties.getPlatform();
 List<String> fallbackResources = new ArrayList<>();
 fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
 fallbackResources.add("classpath*:" + fallback + ".sql");
 return getResources(propertyName, fallbackResources, false);
}

1) fallback = "schema", platform="all",會(huì)自動(dòng)執(zhí)行根目錄下:schema-all.sql 或schema.sql 文件

2) fallback = "data", platform="all",會(huì)自動(dòng)執(zhí)行根目錄下:data-all.sql 或data.sql 文件

isEnabled() 方法判斷是否開啟了自動(dòng)執(zhí)行腳本

有三種模式:NEVER,EMBEDDED(默認(rèn)),Always

疑問(wèn):用EMBEDDED模式返回false,開關(guān)關(guān)閉,不執(zhí)行腳本,這是為啥呢?

用Always模式則每次啟動(dòng)spring boot重復(fù)執(zhí)行腳本(創(chuàng)建表腳本都是先判斷有沒(méi)有表,有則刪除后重建)

private boolean isEnabled() {
 DataSourceInitializationMode mode = this.properties.getInitializationMode();
 if (mode == DataSourceInitializationMode.NEVER) {
   return false;
 }
 if (mode == DataSourceInitializationMode.EMBEDDED && !isEmbedded()) {
   return false;
 }
 return true;
}

3.7 通過(guò)配置文件指定需要執(zhí)行腳本

schema:
 - classpath:department.sql

創(chuàng)建出的 department 表
Spring Boot中如何使用JDBC

四、JdbcTemplate

JdbcTemplateAutoConfiguration.java 文件 自動(dòng)注入了JdbcTemplate。(JdbcTemplate用來(lái)操作數(shù)據(jù)庫(kù))

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(JdbcProperties.class)
@Import({ JdbcTemplateConfiguration.class, NamedParameterJdbcTemplateConfiguration.class })
public class JdbcTemplateAutoConfiguration {

}

五、配置Swagger用來(lái)測(cè)試

5.1 pom.xml文件 添加swagger依賴

<!-- swagger -->
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger2</artifactId>
 <version>2.9.2</version>
</dependency>
<dependency>
 <groupId>io.springfox</groupId>
 <artifactId>springfox-swagger-ui</artifactId>
 <version>2.9.2</version>
</dependency>

5.2 添加SwaggerConfig.java文件

package com.jackson0714.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

   @Bean
   public Docket createRestApi(){
       return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
               .select()
               .apis(RequestHandlerSelectors.any())
               .paths(PathSelectors.any()).build();
   }

   private ApiInfo apiInfo(){
       return new ApiInfoBuilder()
               .title("玩轉(zhuǎn)Spring Boot 接口文檔")
               .description("This is a restful api document of Spring Boot.")
               .version("1.0")
               .build();
   }

}

5.3 訪問(wèn)Swagger文檔

http://localhost:8081/swagger-ui.html
Spring Boot中如何使用JDBC

回到頂部

六、測(cè)試

6.1 新增部門

@ApiOperation(value = "1.新增部門")
@ApiImplicitParams({
 @ApiImplicitParam(name = "name", value = "部門名稱")
})
@PostMapping("/create")
public int createDepartment(@RequestParam String name) {
 String sql = String.format("insert into department(departmentName) value('%s')", name);
 int result = jdbcTemplate.update(sql);
 return result;
}

Spring Boot中如何使用JDBC
表記錄
Spring Boot中如何使用JDBC

6.2 查詢所有部門

@ApiOperation(value = "2.查詢所有部門")
@GetMapping("/getAllDepartment")
public List<Map<String, Object>> getAllDepartment() {
 List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
 return list;
}

Spring Boot中如何使用JDBC

6.3 根據(jù)id查詢某個(gè)部門

@ApiOperation(value = "3.根據(jù)id查詢某個(gè)部門")
@ApiImplicitParams({
 @ApiImplicitParam(name = "id", value = "需要查詢的部門id")
})
@GetMapping("/{id}")
public Map<String, Object> getDepartmentById(@PathVariable Long id) {
 String sql = "select * from department where id = " + id;
 List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
 return list.get(0);
}

Spring Boot中如何使用JDBC

6.4 根據(jù)id更新部門名稱

@ApiOperation(value = "根據(jù)id更新部門名稱")
@ApiImplicitParams({
 @ApiImplicitParam(name = "id", value = "需要更新的部門id"),
 @ApiImplicitParam(name = "name", value = "需要更新的部門名稱")
})
@PostMapping("/update")
public int updateDepartmentById(@RequestParam Long id, @RequestParam String name) {
 String sql = String.format("update department set departmentName = '%s' where id = %d", name, id);
 int result = jdbcTemplate.update(sql);
 return result;
}

Spring Boot中如何使用JDBC

6.5 根據(jù)id刪除部門

@ApiOperation(value = "根據(jù)id刪除部門")
@ApiImplicitParams({
 @ApiImplicitParam(name = "id", value = "需要?jiǎng)h除的部門id")
})
@PostMapping("/delete")
public int deleteDepartment(@RequestParam Long id) {
 String sql = String.format("delete from department where id = %d", id);
 int result = jdbcTemplate.update(sql);
 return result;
}

Spring Boot中如何使用JDBC

七、報(bào)錯(cuò)和解決方案:

7.1 問(wèn)題1

java.sql.SQLException:null, message from server: "Host 'Siri' is not allowed to connect to this MySQL server"
Spring Boot中如何使用JDBC
解決方案:
執(zhí)行命令:

use mysql;
select host from user;
update user set host = '%' where user = 'root'

執(zhí)行結(jié)果:

Query OK, 1 row affected

如下圖所示:
Spring Boot中如何使用JDBC

7.2 問(wèn)題2

Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.
Spring Boot中如何使用JDBC
解決方案:
配置spring.datasource.url 時(shí),增加參數(shù):serverTimezone=UTC
Spring Boot中如何使用JDBC

到此,相信大家對(duì)“Spring Boot中如何使用JDBC”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI