這里演示的是h2databse示例,所以簡單的介紹普及下h2database相關知識
H2數據庫是一個開源的關系型數據庫。
H2是一個嵌入式數據庫引擎,采用java語言編寫,不受平台的限制,同時H2提供了一個十分方便的web控制台用於操作和管理數據庫內容。它還提供兼容模式,可以兼容一些主流的數據庫,因此采用H2作為開發期的數據庫非常方便。
H2數據庫特點:
-
短小精干。
-
Java編寫,可使用GCJ和IKVM.NET編譯。
-
同時支持網絡版和嵌入式版本,另外還提供了內存版。
-
有比較好的兼容性,支持相當標准的sql標准,支持集群。
這里說下JdbcTemplate,之所以會出現JdbcTemplate,我個人加上我自己的一些想法,傳統的JDBC的高耦合性和許多重復性增刪改查,使得JDBC的升級版誕生,這一點與MyBatis Plus有共同的特點。而JDBCTemplate正是看到這一點后,對於JDBC進行升級。
關於JDBCTemplate示例,大家可以參考這位朋友寫的示例:https://www.cnblogs.com/janes/p/6971839.html
下面引用下他的關於JdbcTemplate的介紹:
JdbcTemplate是最基本的Spring JDBC模板,這個模板支持簡單的JDBC數據庫訪問功能以及基於索引參數的查詢。
Spring數據訪問模板:在數據庫操作過程中,有很大一部分重復工作,比如事務控制、管理資源以及處理異常等,Spring的模板類處理這些固定部分。同時,應用程序相關的數據訪問在回調的實現中處理,包括語句、綁定參數以及整理結果等。這樣一來,我們只需關心自己的數據訪問邏輯即可。
Spring的JDBC框架承擔了資源管理和異常處理的工作,從而簡化了JDBC代碼,我們只需要編寫從數據庫讀寫數據的必需代碼就萬事大吉了。
一、導入依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-relational-data-access</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、編寫實體
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); } 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; } }
三、編寫啟動類
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())); } }
最終結果是:
該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
方法在新創建的表中安裝一些記錄。方法調用的第一個參數是查詢字符串,最后一個參數(Object
s 的數組)包含要替換為“?”字符的查詢的變量。
補充說明:
Java 8 lambdas很好地映射到單個方法接口,如Spring的RowMapper
。如果您使用的是Java 7或更早版本,則可以輕松插入匿名接口實現,並具有與lambda expresion正文所包含的相同的方法體,並且它可以毫不費力地使用Spring。