本指南將引導您完成使用Spring訪問關係數據的過程。原文閱讀html
您將使用Spring的JdbcTemplate構建一個應用程序來訪問存儲在關係數據庫中的數據。java
大約十五分鐘git
一個喜歡的文本編輯器或者IDEgithub
JDK 1.8 或者更高web
Gradle 4+ 或者 Maven 3.2+spring
你也能夠導入Code 到你的IDE數據庫
Spring Tool Suite (STS)apache
咱們這裏仍然採用STS 導入Code的方式。intellij-idea
1. 打開STS,New————> Import Sprnig Geting Started Content
2. 輸入rela ,搜索找到Relational Data Access
3. 建立一個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; } public Customer() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
4.存儲和檢索數據
Spring提供了一個名爲JdbcTemplate的模板類,能夠輕鬆處理SQL關係數據庫和JDBC。 大多數JDBC代碼都陷入資源獲取,鏈接管理,異常處理和通常錯誤檢查之中,這與代碼的意圖徹底無關。 JdbcTemplate爲您處理全部這些問題。 你所要作的就是專一於手頭的任務。
src/main/java/hello/Application.java
package hello; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; 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; @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())); } }
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的`execute方法來安裝一些DDL。
其次,獲取字符串列表並使用Java 8流,將它們拆分爲Java數組中的名/姓對。
而後使用JdbcTemplate的batchUpdate方法在新建立的表中安裝一些記錄。方法調用的第一個參數是查詢字符串,最後一個參數(Object數組)包含要替換到查詢中的「?」字符的變量。
對於單插入語句,JdbcTemplate的「插入方法很好。 但對於多個插入,最好使用batchUpdate。
使用 ? 經過指示JDBC綁定變量來避免SQL注入攻擊的參數。
最後,您使用查詢方法在表中搜索符合條件的記錄。 您再次使用「?」參數爲查詢建立參數,並在進行調用時傳入實際值。 最後一個參數是用於將每一個結果行轉換爲新的Customer對象的Java 8 lambda。
Java 8 lambda能夠很好地映射到單個方法接口上,好比Spring的RowMapper。 若是您使用的是Java 7或更早版本,那麼您能夠輕鬆插入匿名接口實現,並具備與lambda表達式正文包含的方法體相同的方法體,而且它將在Spring中絕不起做用
您可使用Gradle或Maven從命令行運行應用程序。 或者您能夠構建一個包含全部必需的依賴項,類和資源的可執行JAR文件,並運行該文件。 這使得在整個開發生命週期內跨越不一樣環境等,將服務做爲應用程序發佈,版本化和部署變得很是容易。
咱們仍然使用STS快速生成可執行Jar
F5 刷新Project,咱們能夠看到target 目錄下已經成功生成了可執行jar
若是您正在使用Gradle,則可使用./gradlew bootRun運行該應用程序。 或者您可使用./gradlew構建構建JAR文件。 而後你能夠運行JAR文件:
java -jar build/libs/gs-relational-data-access-0.1.0.jar
若是您使用的是Maven,則可使用./mvnw spring-boot:run來運行該應用程序。 或者,您可使用./mvnw clean包構建JAR文件。 而後你能夠運行JAR文件:
java -jar target/gs-relational-data-access-0.1.0.jar
上述過程將建立一個可運行的JAR。 您也能夠選擇構建經典的WAR文件。
你應該能看到下面的輸出:
源碼:點擊查看
Spring Boot具備許多用於配置和自定義鏈接池的功能,例如鏈接到外部數據庫而不是內存數據庫。 有關更多詳細信息,請參閱用戶指南。