006 使用JDBC和Spring訪問關係型數據庫

原文

https://spring.io/guides/gs/relational-data-access/

直譯

創建一個Customer對象

您將在下面使用的簡單數據訪問邏輯管理客戶的名字和姓氏。要在應用程序級別表示此數據,請創建一個Customer類。

src/main/java/hello/Customer.java

package hello;

public class Customer {
    private long id;
    private String firstName, lastName;

    public Customer(long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

    // getters & setters omitted for brevity
}

存儲和檢索數據

Spring提供了一個名爲的模板類JdbcTemplate,可以輕鬆使用SQL關係數據庫和JDBC。大多數JDBC代碼都陷入資源獲取,連接管理,異常處理和一般錯誤檢查之中,這與代碼要實現的內容完全無關。該JdbcTemplate你負責這一切的。您所要做的就是專注於手頭的任務。

src/main/java/hello/Application.java

package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
public class Application implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... strings) throws Exception {

        log.info("Creating tables");

        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute("CREATE TABLE customers(" +
                "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

        // Split up the array of whole names into an array of first/last names
        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());

        // Use a Java 8 stream to print out each tuple of the list
        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

        // Uses JdbcTemplate's batchUpdate operation to bulk load data
        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

        log.info("Querying for customer records where first_name = 'Josh':");
        jdbcTemplate.query(
                "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
                (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
        ).forEach(customer -> log.info(customer.toString()));
    }
}

@SpringBootApplication 是一個便利註釋,添加了以下所有內容:

  • @Configuration 標記該類作爲應用程序上下文的bean定義的來源。

  • @EnableAutoConfiguration 告訴Spring Boot開始根據類路徑設置,其他bean和各種屬性設置添加bean。

  • @ComponentScan告訴Spring在包中尋找其他組件,配置和服務hello。在這種情況下,沒有任何。

該main()方法使用Spring Boot的SpringApplication.run()方法啓動應用程序。您是否注意到沒有一行XML?也沒有web.xml文件。此Web應用程序是100%純Java,您無需處理配置任何管道或基礎結構。

Spring Boot支持H2,一種內存中的關係數據庫引擎,並自動創建連接。因爲我們使用的是spring-jdbc,所以Spring Boot會自動創建一個JdbcTemplate。該@Autowired JdbcTemplate字段自動加載它並使其可用。

這個Application類實現了Spring Boot CommandLineRunner,這意味着它將run()在加載應用程序上下文後執行該方法。

  • 首先,使用JdbcTemplate’s `execute方法安裝一些DDL 。

  • 其次,您獲取字符串列表並使用Java 8流,將它們拆分爲Java數組中的firstname / lastname對。

  • 然後使用JdbcTemplate’s `batchUpdate方法在新創建的表中安裝一些記錄。方法調用的第一個參數是查詢字符串,最後一個參數(Objects 的數組)包含要替換爲“?”字符的查詢的變量。

對於單個插入語句,JdbcTemplate’s `insert方法很好。但對於多個插件,最好使用batchUpdate。
使用?的參數,以避免SQL注入攻擊通過指示JDBC來綁定變量。
  • 最後,使用該query方法在表中搜索與條件匹配的記錄。您再次使用“?”參數爲查詢創建參數,在進行調用時傳入實際值。最後一個參數是用於將每個結果行轉換爲新Customer對象的Java 8 lambda 。

Java 8 lambdas很好地映射到單個方法接口,如Spring的RowMapper。如果您使用的是Java 7或更早版本,則可以輕鬆插入匿名接口實現,並具有與lambda expresion正文所包含的相同的方法體,並且它可以毫不費力地使用Spring。

構建可執行的JAR

您可以使用Gradle或Maven從命令行運行該應用程序。或者,您可以構建一個包含所有必需依賴項,類和資源的可執行JAR文件,並運行該文件。這使得在整個開發生命週期中,跨不同環境等將服務作爲應用程序發佈,版本和部署變得容易。

如果您使用的是Gradle,則可以使用./gradlew bootRun。或者您可以使用構建JAR文件./gradlew build。然後你可以運行JAR文件:

java -jar build / libs / gs-relational-data-access-0.1.0.jar

如果您使用的是Maven,則可以使用該應用程序運行該應用程序./mvnw spring-boot:run。或者您可以使用構建JAR文件./mvnw clean package。然後你可以運行JAR文件:

java -jar target / gs-relational-data-access-0.1.0.jar

上面的過程將創建一個可運行的JAR。您也可以選擇構建經典WAR文件。
您應該看到以下輸出:

2015-06-19 10:58:31.152 INFO 67731 --- [main] hello.Application:創建表格
2015-06-19 10:58:31.219 INFO 67731 --- [main] hello.Application:爲John Woo插入客戶記錄
2015-06-19 10:58:31.220 INFO 67731 --- [主要] hello.Application:爲Jeff Dean插入客戶記錄
2015-06-19 10:58:31.220 INFO 67731 --- [主要] hello.Application:插入Josh Bloch的客戶記錄
2015-06-19 10:58:31.220 INFO 67731 --- [main] hello.Application:爲Josh Long插入客戶記錄
2015-06-19 10:58:31.230 INFO 67731 --- [main] hello.Application:查詢first_name ='Josh'的客戶記錄:
2015-06-19 10:58:31.242 INFO 67731 --- [main] hello.Application:Customer [id = 3,firstName ='Josh',lastName ='Bloch']
2015-06-19 10:58:31.242 INFO 67731 --- [main] hello.Application:Customer [id = 4,firstName ='Josh',lastName ='Long']
2015-06-19 10:58:31.244 INFO 67731 --- [main] hello.Application:在1.693秒內啓動應用程序(JVM運行2.054)

摘要

恭喜!您剛剛使用Spring開發了一個簡單的JDBC客戶端。

Spring Boot具有許多用於配置和自定義連接池的功能,例如連接到外部數據庫而不是內存數據庫。有關更多詳細信息,請參閱“ 用戶指南”。

延伸知識點

java 數據庫驅動的加載機制:SPI

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章