此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data Relational 3.4.4spring-doc.cadn.net.cn

开始

引导设置工作环境的一种简单方法是在 Spring Tools 中或从 Spring Initializr 创建基于 Spring 的项目。spring-doc.cadn.net.cn

首先,您需要设置一个正在运行的数据库服务器。 有关如何配置数据库以进行 R2DBC 访问的信息,请参阅您的供应商文档。spring-doc.cadn.net.cn

要求

Spring Data R2DBC 需要 Spring Framework 6.2.4 及更高版本。spring-doc.cadn.net.cn

在数据库方面, Spring Data R2DBC 需要一个驱动程序来抽象常见的 SQL 功能,而不是特定于供应商的风格。 Spring Data R2DBC 包括对以下数据库的直接支持:spring-doc.cadn.net.cn

如果您使用其他数据库,则您的应用程序将无法启动。 方言部分包含有关如何在这种情况下进行的更多详细信息。spring-doc.cadn.net.cn

世界您好

要在 STS 中创建 Spring 项目,请执行以下作:spring-doc.cadn.net.cn

  1. 转到 File → New → Spring Template Project → Simple Spring Utility Project,并在出现提示时按 Yes。 然后输入项目和包名称,例如org.spring.r2dbc.example.spring-doc.cadn.net.cn

  2. 将以下内容添加到pom.xml文件dependencies元素:spring-doc.cadn.net.cn

  3. 将以下内容添加到 pom.xml 文件中dependencies元素:spring-doc.cadn.net.cn

    <dependencies>
    
      <!-- other dependency elements omitted -->
    
      <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-r2dbc</artifactId>
        <version>3.4.5-SNAPSHOT</version>
      </dependency>
    
      <!-- a R2DBC driver -->
      <dependency>
        <groupId>io.r2dbc</groupId>
        <artifactId>r2dbc-h2</artifactId>
        <version>x.y.z</version>
      </dependency>
    
    </dependencies>
  4. 将 Spring 的 pom.xml 版本更改为spring-doc.cadn.net.cn

    <spring.version>6.2.4</spring.version>
  5. 将 Maven 的 Spring Milestone 存储库的以下位置添加到您的pom.xml使其与您的<dependencies/>元素:spring-doc.cadn.net.cn

    <repositories>
      <repository>
        <id>spring-milestone</id>
        <name>Spring Maven MILESTONE Repository</name>
        <url>https://repo.spring.io/milestone</url>
      </repository>
    </repositories>

您可能还需要将日志记录级别设置为DEBUG以查看一些其他信息。 为此,请编辑application.propertiesfile 中包含以下内容:spring-doc.cadn.net.cn

logging.level.org.springframework.r2dbc=DEBUG

然后,例如,您可以创建一个Person类进行持久化,如下所示:spring-doc.cadn.net.cn

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 + "]";
	}
}

接下来,您需要在数据库中创建一个表结构,如下所示:spring-doc.cadn.net.cn

CREATE TABLE person
  (id VARCHAR(255) PRIMARY KEY,
   name VARCHAR(255),
   age INT);

您还需要一个主应用程序来运行,如下所示:spring-doc.cadn.net.cn

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();
  }
}

When you run the main program, the preceding examples produce output similar to the following:spring-doc.cadn.net.cn

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]

Even in this simple example, there are few things to notice:spring-doc.cadn.net.cn

  • You can create an instance of the central helper class in Spring Data R2DBC (R2dbcEntityTemplate) by using a standard io.r2dbc.spi.ConnectionFactory object.spring-doc.cadn.net.cn

  • The mapper works against standard POJO objects without the need for any additional metadata (though you can, optionally, provide that information — see here.).spring-doc.cadn.net.cn

  • Mapping conventions can use field access.Notice that the Person class has only getters.spring-doc.cadn.net.cn

  • If the constructor argument names match the column names of the stored row, they are used to instantiate the object.spring-doc.cadn.net.cn

Examples Repository

There is a GitHub repository with several examples that you can download and play around with to get a feel for how the library works.spring-doc.cadn.net.cn

Connecting to a Relational Database with Spring

One of the first tasks when using relational databases and Spring is to create a io.r2dbc.spi.ConnectionFactory object by using the IoC container. Make sure to use a supported database and driver.spring-doc.cadn.net.cn

Registering a ConnectionFactory Instance using Java Configuration

The following example shows an example of using Java-based bean metadata to register an instance of io.r2dbc.spi.ConnectionFactory:spring-doc.cadn.net.cn

Registering a io.r2dbc.spi.ConnectionFactory object using Java Configuration
@Configuration
public class ApplicationConfiguration extends AbstractR2dbcConfiguration {

  @Override
  @Bean
  public ConnectionFactory connectionFactory() {
    return …
  }
}

This approach lets you use the standard io.r2dbc.spi.ConnectionFactory instance, with the container using Spring’s AbstractR2dbcConfiguration.As compared to registering a ConnectionFactory instance directly, the configuration support has the added advantage of also providing the container with an ExceptionTranslator implementation that translates R2DBC exceptions to exceptions in Spring’s portable DataAccessException hierarchy for data access classes annotated with the @Repository annotation.This hierarchy and the use of @Repository is described in Spring’s DAO support features.spring-doc.cadn.net.cn

AbstractR2dbcConfiguration also registers DatabaseClient, which is required for database interaction and for Repository implementation.spring-doc.cadn.net.cn

Dialects

Spring Data R2DBC uses a Dialect to encapsulate behavior that is specific to a database or its driver. Spring Data R2DBC reacts to database specifics by inspecting the ConnectionFactory and selects the appropriate database dialect accordingly. If you use a database for which no dialect is available, then your application won’t start up. In that case, you’ll have to ask your vendor to provide a Dialect implementation. Alternatively, you can implement your own Dialect.spring-doc.cadn.net.cn

Dialects are resolved by DialectResolver from a ConnectionFactory, typically by inspecting ConnectionFactoryMetadata. + You can let Spring auto-discover your R2dbcDialect by registering a class that implements org.springframework.data.r2dbc.dialect.DialectResolver$R2dbcDialectProvider through META-INF/spring.factories. DialectResolver discovers dialect provider implementations from the class path using Spring’s SpringFactoriesLoader. To do so:spring-doc.cadn.net.cn

  1. Implement your own Dialect.spring-doc.cadn.net.cn

  2. Implement a R2dbcDialectProvider returning the Dialect.spring-doc.cadn.net.cn

  3. Register the provider by creating a spring.factories resource under META-INF and perform the registration by adding a line
    org.springframework.data.r2dbc.dialect.DialectResolver$R2dbcDialectProvider=<fully qualified name of your R2dbcDialectProvider>spring-doc.cadn.net.cn