開始使用
啟動工作環境的簡單方法是在 Spring Tools 或 Spring Initializr 中建立一個基於 Spring 的專案。
首先,您需要設定一個正在運行的資料庫伺服器。請參閱您的供應商文件,了解如何為 R2DBC 存取設定您的資料庫。
需求
Spring Data R2DBC 需要 Spring Framework 6.2.0 及以上版本。
在資料庫方面,Spring Data R2DBC 需要一個 驅動程式 來抽象化跨供應商特定風格的通用 SQL 功能。Spring Data R2DBC 包含對以下資料庫的直接支援
-
H2 (
io.r2dbc:r2dbc-h2
) -
MariaDB (
org.mariadb:r2dbc-mariadb
) -
Microsoft SQL Server (
io.r2dbc:r2dbc-mssql
) -
MySQL (
io.asyncer:r2dbc-mysql
) -
jasync-sql MySQL (
com.github.jasync-sql:jasync-r2dbc-mysql
) -
Postgres (
io.r2dbc:r2dbc-postgresql
) -
Oracle (
com.oracle.database.r2dbc:oracle-r2dbc
)
如果您使用不同的資料庫,則您的應用程式將無法啟動。方言 章節包含有關如何在這種情況下繼續操作的更多詳細資訊。
Hello World
若要在 STS 中建立 Spring 專案
-
前往 File → New → Spring Template Project → Simple Spring Utility Project,並在出現提示時按 Yes。然後輸入專案和套件名稱,例如
org.spring.r2dbc.example
。 -
將以下內容新增至
pom.xml
檔案的dependencies
元素 -
將以下內容新增至 pom.xml 檔案的
dependencies
元素<dependencies> <!-- other dependency elements omitted --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-r2dbc</artifactId> <version>3.4.0</version> </dependency> <!-- a R2DBC driver --> <dependency> <groupId>io.r2dbc</groupId> <artifactId>r2dbc-h2</artifactId> <version>x.y.z</version> </dependency> </dependencies>
-
將 pom.xml 中的 Spring 版本變更為
<spring.version>6.2.0</spring.version>
-
將以下 Spring Milestone 儲存庫位置新增至您的
pom.xml
,使其與您的<dependencies/>
元素位於同一層級<repositories> <repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories>
此儲存庫也可在此處 瀏覽。
您可能也想將記錄層級設定為 DEBUG
以查看一些其他資訊。若要執行此操作,請編輯 application.properties
檔案以具有以下內容
logging.level.org.springframework.r2dbc=DEBUG
然後,您可以例如建立一個 Person
類別來持久化,如下所示
public class Person {
private final String id;
private final String name;
private final int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
接下來,您需要在資料庫中建立資料表結構,如下所示
CREATE TABLE person
(id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255),
age INT);
您還需要一個主要應用程式來執行,如下所示
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import reactor.test.StepVerifier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
public class R2dbcApp {
private static final Log log = LogFactory.getLog(R2dbcApp.class);
public static void main(String[] args) {
ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:h2:mem:///test?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
R2dbcEntityTemplate template = new R2dbcEntityTemplate(connectionFactory);
template.getDatabaseClient().sql("CREATE TABLE person" +
"(id VARCHAR(255) PRIMARY KEY," +
"name VARCHAR(255)," +
"age INT)")
.fetch()
.rowsUpdated()
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
template.insert(Person.class)
.using(new Person("joe", "Joe", 34))
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
template.select(Person.class)
.first()
.doOnNext(it -> log.info(it))
.as(StepVerifier::create)
.expectNextCount(1)
.verifyComplete();
}
}
當您執行主要程式時,先前的範例會產生類似於以下的輸出
2018-11-28 10:47:03,893 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 310 - Executing SQL statement [CREATE TABLE person
(id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255),
age INT)]
2018-11-28 10:47:04,074 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 908 - Executing SQL statement [INSERT INTO person (id, name, age) VALUES($1, $2, $3)]
2018-11-28 10:47:04,092 DEBUG amework.core.r2dbc.DefaultDatabaseClient: 575 - Executing SQL statement [SELECT id, name, age FROM person]
2018-11-28 10:47:04,436 INFO org.spring.r2dbc.example.R2dbcApp: 43 - Person [id='joe', name='Joe', age=34]
即使在這個簡單的範例中,也有一些需要注意的事項
-
您可以使用標準
io.r2dbc.spi.ConnectionFactory
物件,來建立 Spring Data R2DBC(R2dbcEntityTemplate
)中樞輔助類別的實例。 -
mapper 可以針對標準 POJO 物件運作,而無需任何額外的中繼資料(儘管您可以選擇性地提供該資訊 — 請參閱此處)。
-
對應慣例可以使用欄位存取。請注意,
Person
類別只有 getter。 -
如果建構子引數名稱與儲存列的欄名稱稱相符,則會使用它們來實例化物件。
範例 Repository
有一個 GitHub 儲存庫,其中包含多個範例,您可以下載並試用以了解程式庫的運作方式。
使用 Spring 連接到關聯式資料庫
使用關聯式資料庫和 Spring 時,首要任務之一是使用 IoC 容器建立 io.r2dbc.spi.ConnectionFactory
物件。請務必使用支援的資料庫和驅動程式。
使用 Java Configuration 註冊 ConnectionFactory
實例
以下範例顯示使用基於 Java 的 bean 中繼資料來註冊 io.r2dbc.spi.ConnectionFactory
實例的範例
io.r2dbc.spi.ConnectionFactory
物件@Configuration
public class ApplicationConfiguration extends AbstractR2dbcConfiguration {
@Override
@Bean
public ConnectionFactory connectionFactory() {
return …
}
}
此方法可讓您使用標準 io.r2dbc.spi.ConnectionFactory
實例,容器使用 Spring 的 AbstractR2dbcConfiguration
。與直接註冊 ConnectionFactory
實例相比,組態支援還具有額外的優勢,即還為容器提供了一個 ExceptionTranslator
實作,該實作將 R2DBC 異常轉換為 Spring 可移植的 DataAccessException
層次結構,用於使用 @Repository
註解的資料存取類別。此層次結構和 @Repository
的使用在Spring 的 DAO 支援功能中進行了描述。
AbstractR2dbcConfiguration
還註冊了 DatabaseClient
,這是資料庫互動和 Repository 實作所需的。
方言
Spring Data R2DBC 使用 Dialect
來封裝特定於資料庫或其驅動程式的行為。Spring Data R2DBC 通過檢查 ConnectionFactory
並相應地選擇適當的資料庫方言,來對資料庫的特定性做出反應。如果您使用的資料庫沒有可用的方言,則您的應用程式將無法啟動。在這種情況下,您必須要求您的供應商提供 Dialect
實作。或者,您可以實作您自己的 Dialect
。
方言由
|