SQL 数据库
Spring 框架为使用 SQL 数据库提供了广泛的支持,从直接通过 JDBC 访问,使用Jdbc客户端或Jdbc模板完成“对象关系映射”技术,如Hibernate。Spring Data 提供了额外功能层面:创建存储 库直接从接口实现,并使用约定从方法名生成查询。
配置数据源
| 请参阅“作指南”中的“配置自定义数据源”部分,获取更高级的示例,通常用于完全控制数据源的配置。 |
嵌入式数据库支持
通常通过内存内嵌入式数据库开发应用程序非常方便。 显然,内存数据库不提供持久存储。 你需要在申请开始时填充数据库,并准备好在申请结束时丢弃数据。
| “作指南”部分包含如何初始化数据库的部分。 |
Spring Boot 可以自动配置嵌入式 H2、HSQL 和 Derby 数据库。
你无需提供任何连接网址。
你只需要在你想使用的嵌入式数据库中添加构建依赖。
如果类路径上有多个嵌入式数据库,则设置spring.datasource.embedded-database-connection配置属性用于控制使用哪一种。
将属性设置为没有禁用嵌入数据库的自动配置。
|
如果你在测试中使用此功能,你可能会发现无论使用多少应用上下文,整个测试套件都会重复使用同一个数据库。
如果你想确保每个上下文都有独立的嵌入式数据库,你应该设置 |
例如,典型的POM依赖关系如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
你需要依赖春季-JDBC嵌入数据库的自动配置。
在这个例子中,它通过传递方式被拉入Spring-boot-starter-data-jpa. |
如果你因某种原因配置了嵌入式数据库的连接URL,请务必确保该数据库的自动关闭功能被禁用。
如果你用H2,应该用DB_CLOSE_ON_EXIT=假去做这件事。
如果你用 HSQLDB,应该确保shutdown=true未被使用。
禁用数据库自动关闭功能后,Spring Boot 可以控制数据库的关闭时间,从而确保在不再需要访问数据库时关闭。 |
连接生产数据库
生产数据库连接也可以通过池化自动配置数据来源.
DataSource配置
DataSource 配置由外部配置属性控制,该属性在spring.datasource.*.
例如,你可以声明以下部分application.properties:
-
Properties
-
YAML
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring:
datasource:
url: "jdbc:mysql://localhost/test"
username: "dbuser"
password: "dbpass"
你至少应该通过设置spring.datasource.url财产。
否则,Spring Boot 会尝试自动配置嵌入式数据库。 |
Spring Boot 可以从该 URL 推断大多数数据库的 JDBC 驱动程序类。
如果你需要指定特定类别,可以使用Spring.datasource.driver-class-name财产。 |
用于汇聚数据来源要被创建,我们需要能够验证一个有效的Drivers课程是开放的,所以我们会先确认这一点再做任何事。
换句话说,如果你设置spring.datasource.driver-class-name=com.mysql.jdbc.Driver那么该类必须是可加载的。 |
看DataSourceProperties(数据源属性)更多支持选项的API文档。
这些都是无论实际实施如何都能正常使用的标准选项。
也可以通过使用相应的前缀(春.数据源.光。*,spring.datasource.tomcat.*,spring.datasource.dbcp2.*和spring.datasource.oracleucp.*).
详情请参阅你所使用的连接池实现文档。
例如,如果你使用Tomcat的连接池,你可以自定义许多额外设置,如下示例所示:
-
Properties
-
YAML
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true
spring:
datasource:
tomcat:
max-wait: 10000
max-active: 50
test-on-borrow: true
这会让池等待10000毫秒后,如果没有连接可用才抛出异常,限制连接数上限为50个,并在从池中借用连接前验证连接。
支持的连接池
Spring Boot 使用以下算法来选择特定实现:
-
我们更喜欢 HikariCP,因为它的性能和并发性。 如果有HikariCP,我们总是选择它。
-
否则,如果Tomcat池化
数据来源我们都用它。 -
否则,如果有Commons DBCP2,我们就用它。
-
如果 HikariCP、Tomcat 和 DBCP2 都不可用,而 Oracle UCP 可用,我们就用它。
如果你使用了Spring-boot-Starter-JDBC或Spring-boot-starter-data-jpa首先,你会自动获得对HikariCP的依赖。 |
你可以完全绕过那个算法,通过设置spring.datasource.type财产。
如果你在 Tomcat 容器中运行应用程序,这一点尤为重要,因为Tomcat-JDBC默认提供。
-
光之党
-
Tomcat池化
数据来源 -
共享版DBCP2
-
Oracle UCP &
OracleDataSource -
Spring Framework 的
SimpleDriverDataSource -
PostgreSQL
PGSimpleDataSource -
C3P0
-
维布尔
连接JNDI数据源
如果你将 Spring Boot 应用部署到应用服务器,可能想利用应用服务器内置功能配置和管理数据源,并通过 JNDI 访问数据源。
这Spring.datasource.jndi-name属性可以作为spring.datasource.url,spring.datasource.username和spring.datasource.password(春.datasource.password)访问数据来源来自特定的JNDI地点。
例如,以下部分application.properties展示了如何访问定义的JBoss AS数据来源:
-
Properties
-
YAML
spring.datasource.jndi-name=java:jboss/datasources/customers
spring:
datasource:
jndi-name: "java:jboss/datasources/customers"
使用 JdbcTemplate
斯普林斯Jdbc模板和NamedParameterJdbcTemplate类是自动配置的,你可以直接把它们自动接线到你自己的豆子里,如下示例所示:
-
Java
-
Kotlin
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void doSomething() {
this.jdbcTemplate ...
}
}
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.stereotype.Component
@Component
class MyBean(private val jdbcTemplate: JdbcTemplate) {
fun doSomething() {
jdbcTemplate.execute("delete from customer")
}
}
你可以通过使用spring.jdbc.template.*性质,如下例所示:
-
Properties
-
YAML
spring.jdbc.template.max-rows=500
spring:
jdbc:
template:
max-rows: 500
如果需要调优 SQL 异常,你可以自定义SQLExceptionTranslatorBEAN 使其与自动配置关联Jdbc模板.
这NamedParameterJdbcTemplate重复使用。Jdbc模板幕后实例。
如果不止一个Jdbc模板定义且不存在主要候选人,则NamedParameterJdbcTemplate不是自动配置的。 |
使用 JdbcClient
斯普林斯Jdbc客户端是基于 A 的存在自动配置的NamedParameterJdbcTemplate.
你也可以直接把它注射到自己的豆子里,如下例所示:
-
Java
-
Kotlin
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcClient jdbcClient;
public MyBean(JdbcClient jdbcClient) {
this.jdbcClient = jdbcClient;
}
public void doSomething() {
this.jdbcClient ...
}
}
import org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.stereotype.Component
@Component
class MyBean(private val jdbcClient: JdbcClient) {
fun doSomething() {
jdbcClient.sql("delete from customer").update()
}
}
如果你依赖自动配置来创建底层Jdbc模板,任何使用spring.jdbc.template.*客户也会考虑房产。
JPA与春季数据JPA
Java 持久化 API 是一种标准技术,允许你将对象“映射”到关系型数据库。
这Spring-boot-starter-data-jpaPOM提供了一个快速入门的方式。
它提供了以下关键依赖关系:
-
Hibernate:最受欢迎的JPA实现之一。
-
Spring Data JPA:帮助你实现基于 JPA 的仓库。
-
Spring ORM:来自 Spring 框架的核心 ORM 支持。
| 这里我们不会详细介绍JPA或春季数据。 你可以按照 spring.io 的《用JPA访问数据》指南,阅读Spring Data的JPA和休眠参考文档。 |
实体类别
传统上,JPA “实体”类在persistence.xml文件。
使用 Spring Boot 时,不需要这个文件,而是使用“实体扫描”来替代。
默认情况下,自动配置包会被扫描。
任何标注为@Entity,@Embeddable或@MappedSuperclass被考虑。
一个典型的实体类类似于以下示例:
-
Java
-
Kotlin
import java.io.Serializable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
// ... additional members, often include @OneToMany mappings
protected City() {
// no-args constructor required by JPA spec
// this one is protected since it should not be used directly
}
public City(String name, String state) {
this.name = name;
this.state = state;
}
public String getName() {
return this.name;
}
public String getState() {
return this.state;
}
// ... etc
}
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.Id
import java.io.Serializable
@Entity
class City : Serializable {
@Id
@GeneratedValue
private val id: Long? = null
@Column(nullable = false)
var name: String? = null
private set
// ... etc
@Column(nullable = false)
var state: String? = null
private set
// ... additional members, often include @OneToMany mappings
protected constructor() {
// no-args constructor required by JPA spec
// this one is protected since it should not be used directly
}
constructor(name: String?, state: String?) {
this.name = name
this.state = state
}
}
您可以通过以下方式自定义实体扫描位置@EntityScan注解。
请参阅“作指南”中“弹簧配置的独立@Entity定义部分。 |
Spring Data JPA 仓库
Spring Data JPA 仓库是你可以定义用于访问数据的接口。
JPA 查询是从你的方法名称自动生成的。
例如,一个城市仓库接口可能会声明一个findAllByState(字符串状态)寻找给定州内所有城市的方法。
对于更复杂的查询,你可以用 Spring Data 的注释来标记你的方法查询注解。
你可以自定义位置来查找仓库@EnableJpaRepositories. |
以下示例展示了典型的 Spring Data 存储库接口定义:
-
Java
-
Kotlin
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.City;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
public interface CityRepository extends Repository<City, Long> {
Page<City> findAll(Pageable pageable);
City findByNameAndStateAllIgnoringCase(String name, String state);
}
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.City
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.Repository
interface CityRepository : Repository<City, Long> {
fun findAll(pageable: Pageable?): Page<City>?
fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): City?
}
Spring Data JPA 仓库支持三种不同的引导模式:默认模式、延迟模式和懒模式。
要启用延迟或懒惰引导,设置spring.data.jpa.repositories.bootstrap-mode属性到递 延或懒惰分别。
使用延迟或懒惰引导时,自动配置实体管理器工厂建设者将使用上下文的异步任务执行器,如果有的话,作为引导执行者。
如果存在多个,则被命名为applicationTaskExecutor将被使用。
|
使用延迟或懒惰引导时,确保在应用上下文引导阶段结束后推迟对JPA基础设施的任何访问。
你可以使用 |
| 我们才刚刚触及了Spring Data JPA的表面。 完整详情请参阅 Spring Data JPA 参考文档。 |
Spring Data Envers Repositories
如果有 Spring Data Envers,JPA 仓库会自动配置支持典型的 Envers 查询。
要使用 Spring Data Envers,确保你的仓库扩展到修订仓库如下例所示:
-
Java
-
Kotlin
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.Country;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.history.RevisionRepository;
public interface CountryRepository extends RevisionRepository<Country, Long, Integer>, Repository<Country, Long> {
Page<Country> findAll(Pageable pageable);
}
import org.springframework.boot.docs.data.sql.jpaandspringdata.entityclasses.Country
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.Repository
import org.springframework.data.repository.history.RevisionRepository
interface CountryRepository :
RevisionRepository<Country, Long, Int>,
Repository<Country, Long> {
fun findAll(pageable: Pageable?): Page<Country>?
}
| 欲了解更多细节,请查阅 Spring Data Envers 参考文档。 |
创建和丢弃JPA数据库
默认情况下,只有使用嵌入式数据库(H2、HSQL或Derby)时,JPA数据库才会自动创建。
你可以通过以下方式显式配置JPA设置Spring.jpa.*性能。
例如,创建和删除表格时,你可以在application.properties:
-
Properties
-
YAML
spring.jpa.hibernate.ddl-auto=create-drop
spring:
jpa:
hibernate.ddl-auto: "create-drop"
Hibernate内部属性的名称(如果你记得更清楚的话)是休眠。HBM2DDDL.自动.
你可以通过以下方式设置它和其他 Hibernate 原生属性spring.jpa.properties.*(在添加实体管理器前,前缀会被去除)。
以下一行展示了为休眠设置JPA属性的示例: |
-
Properties
-
YAML
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring:
jpa:
properties:
hibernate:
"globally_quoted_identifiers": "true"
前例中的直线传递的值为true对于hibernate.globally_quoted_identifiers属性归休眠实体管理器。
默认情况下,DDL的执行(或验证)会被推迟到,应用上下文已经开始了。
开放实体管理器(View in View)
如果你运行的是网页应用,Spring Boot 默认会注册OpenEntityManagerInViewInterceptor应用“在视图中打开实体管理器”模式,以允许在网页视图中进行懒散加载。如果你不希望出现这种行为,应该设置为Spring.JPA.开放-视野自false在你的application.properties.
春季数据 JDBC
当必要的依赖依赖在类路径上时,Spring Boot 会自动配置 Spring Data 的 JDBC 仓库。它们可以通过单一依赖添加到你的项目中Spring-boot-Starter-Data-JDBC. 如有必要,您可以通过添加@EnableJdbcRepositories注释或摘要Jdbc配置你的应用子职业。
| 有关Spring Data JDBC的完整详细信息,请参见参考文档。 |
使用 H2 的网页控制台
-
你正在开发一个基于 servlet 的网页应用。
-
com.h2database:h2在阶级路径上。 -
你正在使用Spring Boot的开发者工具。
如果你没有使用 Spring Boot 的开发者工具,但仍想使用 H2 的控制台,你可以配置spring.h2.console.enabled具有true. |
H2主机仅供开发期间使用,所以你要注意spring.h2.console.enabled未被设置为true正在生产中。 |
在安全应用中访问H2控制台
H2 控制台使用帧,且仅面向开发,未实现 CSRF 保护措施。如果您的应用使用 Spring Security,您需要配置为
-
禁用对控制台请求的CSRF保护,
-
设置头部
X帧选项自同一起源控制台的回复。
关于CSRF和X-Frame-Options头的更多信息,可以在Spring安全参考指南中找到。
在简单的设置中,一个安全滤网链例如,可以使用以下方法:
-
Java
-
Kotlin
import org.springframework.boot.security.autoconfigure.web.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
import org.springframework.security.web.SecurityFilterChain;
@Profile("dev")
@Configuration(proxyBeanMethods = false)
public class DevProfileSecurityConfiguration {
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) {
http.securityMatcher(PathRequest.toH2Console());
http.authorizeHttpRequests(yourCustomAuthorization());
http.csrf(CsrfConfigurer::disable);
http.headers((headers) -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
return http.build();
}
}
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.security.config.Customizer
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
@Profile("dev")
@Configuration(proxyBeanMethods = false)
class DevProfileSecurityConfiguration {
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
fun h2ConsoleSecurityFilterChain(http: HttpSecurity): SecurityFilterChain {
return http.authorizeHttpRequests(yourCustomAuthorization())
.csrf { csrf -> csrf.disable() }
.headers { headers -> headers.frameOptions { frameOptions -> frameOptions.sameOrigin() } }
.build()
}
}
| H2控制台仅设计用于开发阶段。在生产环境中,禁用CSRF保护或允许网站使用帧可能带来严重的安全风险。 |
PathRequest.toH2Console()当控制台路径被自定义时,还返回正确的请求匹配器。 |
使用 jOOQ
jOOQ 面向对象查询(jOOQ)是 Data Geekery 推出的一款热门产品,它从数据库生成 Java 代码,并通过其流畅 API 构建类型安全 SQL 查询。商业版和开源版均可与 Spring Boot 一起使用。
代码生成
为了使用 jOOQ 类型安全查询,你需要从数据库模式中生成 Java 类。你可以按照 jOOQ 用户手册中的说明作。如果你使用Jooq-Codegen-Maven插件,你还会使用Spring靴启动父“parent POM”,你可以放心省略插件的<版本>标记。 你也可以使用 Spring Boot 定义的版本变量(例如h2.version)以声明插件的数据库依赖。以下列表展示了一个示例:
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<executions>
...
</executions>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<configuration>
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/yourdatabase</url>
</jdbc>
<generator>
...
</generator>
</configuration>
</plugin>
使用 DSLContext
jOOQ 提供的流流 API 是通过DSLContext接口。 Spring Boot 会自动配置 aDSLContext作为一个Spring Bean,并将其连接到你的应用程序数据来源. 使用DSLContext你可以将其注入,如下示例所示:
-
Java
-
Kotlin
import java.util.GregorianCalendar;
import java.util.List;
import org.jooq.DSLContext;
import org.springframework.stereotype.Component;
import static org.springframework.boot.docs.data.sql.jooq.dslcontext.Tables.AUTHOR;
@Component
public class MyBean {
private final DSLContext create;
public MyBean(DSLContext dslContext) {
this.create = dslContext;
}
}
import org.jooq.DSLContext
import org.springframework.stereotype.Component
import java.util.GregorianCalendar
@Component
class MyBean(private val create: DSLContext) {
}
jOOQ 手册通常使用一个名为创造以保持DSLContext. |
然后你可以使用DSLContext构建你的查询,如下示例所示:
-
Java
-
Kotlin
public List<GregorianCalendar> authorsBornAfter1980() {
return this.create.selectFrom(AUTHOR)
.where(AUTHOR.DATE_OF_BIRTH.greaterThan(new GregorianCalendar(1980, 0, 1)))
.fetch(AUTHOR.DATE_OF_BIRTH);
fun authorsBornAfter1980(): List<GregorianCalendar> {
return create.selectFrom<Tables.TAuthorRecord>(Tables.AUTHOR)
.where(Tables.AUTHOR?.DATE_OF_BIRTH?.greaterThan(GregorianCalendar(1980, 0, 1)))
.fetch(Tables.AUTHOR?.DATE_OF_BIRTH)
}
jOOQ SQL 方言
除非spring.jooq.sql方言属性已配置,Spring Boot 会确定用于数据源的 SQL 方言。
如果 Spring Boot 无法检测方言,它会用默认值.
| Spring Boot 只能自动配置开源版本 jOOQ 支持的方言。 |
定制jOOQ
更高级的自定义还可以通过自定义来实现DefaultConfigurationCustomizer在创建配置 @Bean.
这优先于自动配置所应用的任何内容。
使用 R2DBC
连接工厂配置由外部配置属性控制,在spring.r2dbc.*.
例如,你可以声明以下部分application.properties:
-
Properties
-
YAML
spring.r2dbc.url=r2dbc:postgresql://localhost/test
spring.r2dbc.username=dbuser
spring.r2dbc.password=dbpass
spring:
r2dbc:
url: "r2dbc:postgresql://localhost/test"
username: "dbuser"
password: "dbpass"
| 你不需要指定驱动程序类名称,因为 Spring Boot 是从 R2DBC 的连接工厂发现中获取驱动的。 |
至少应该提供网址。
URL中指定的信息优先于单个属性,即名称,用户名,密码以及池塘选项。 |
| “作指南”部分包含如何初始化数据库的部分。 |
为了定制由连接工厂,也就是说,设置你不希望(或无法)在中央数据库配置中配置的特定参数,你可以使用ConnectionFactoryOptionsBuilderCustomizer @Bean.
以下示例展示了如何手动覆盖数据库端口,同时其余选项则取自应用配置:
-
Java
-
Kotlin
import io.r2dbc.spi.ConnectionFactoryOptions;
import org.springframework.boot.r2dbc.autoconfigure.ConnectionFactoryOptionsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyR2dbcConfiguration {
@Bean
public ConnectionFactoryOptionsBuilderCustomizer connectionFactoryPortCustomizer() {
return (builder) -> builder.option(ConnectionFactoryOptions.PORT, 5432);
}
}
import io.r2dbc.spi.ConnectionFactoryOptions
import org.springframework.boot.r2dbc.autoconfigure.ConnectionFactoryOptionsBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)
class MyR2dbcConfiguration {
@Bean
fun connectionFactoryPortCustomizer(): ConnectionFactoryOptionsBuilderCustomizer {
return ConnectionFactoryOptionsBuilderCustomizer { builder ->
builder.option(ConnectionFactoryOptions.PORT, 5432)
}
}
}
以下示例展示了如何设置一些PostgreSQL连接选项:
-
Java
-
Kotlin
import java.util.HashMap;
import java.util.Map;
import io.r2dbc.postgresql.PostgresqlConnectionFactoryProvider;
import org.springframework.boot.r2dbc.autoconfigure.ConnectionFactoryOptionsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class MyPostgresR2dbcConfiguration {
@Bean
public ConnectionFactoryOptionsBuilderCustomizer postgresCustomizer() {
Map<String, String> options = new HashMap<>();
options.put("lock_timeout", "30s");
options.put("statement_timeout", "60s");
return (builder) -> builder.option(PostgresqlConnectionFactoryProvider.OPTIONS, options);
}
}
import io.r2dbc.postgresql.PostgresqlConnectionFactoryProvider
import org.springframework.boot.r2dbc.autoconfigure.ConnectionFactoryOptionsBuilderCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration(proxyBeanMethods = false)
class MyPostgresR2dbcConfiguration {
@Bean
fun postgresCustomizer(): ConnectionFactoryOptionsBuilderCustomizer {
val options: MutableMap<String, String> = HashMap()
options["lock_timeout"] = "30s"
options["statement_timeout"] = "60s"
return ConnectionFactoryOptionsBuilderCustomizer { builder ->
builder.option(PostgresqlConnectionFactoryProvider.OPTIONS, options)
}
}
}
当连接工厂豆子和普通JDBC都有供应数据来源自动配置会退后。
如果你想保留JDBC数据来源自动配置,并且能够接受在被动应用中使用阻断JDBC API的风险,添加@Import(DataSourceAutoConfiguration.class)在@Configuration在你的应用中重新启用它。
嵌入式数据库支持
类似于JDBC支持,Spring Boot可以自动配置嵌入式数据库以进行响应式使用。 你无需提供任何连接网址。 你只需包含一个构建依赖于你想使用的嵌入式数据库,如下示例所示:
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-h2</artifactId>
<scope>runtime</scope>
</dependency>
|
如果你在测试中使用此功能,你可能会发现无论使用多少应用上下文,整个测试套件都会重复使用同一个数据库。
如果你想确保每个上下文都有独立的嵌入式数据库,你应该设置 |
使用 DatabaseClient
一个数据库客户端豆子是自动配置的,你可以直接自动接线到自己的豆子上,如下示例所示:
-
Java
-
Kotlin
import java.util.Map;
import reactor.core.publisher.Flux;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final DatabaseClient databaseClient;
public MyBean(DatabaseClient databaseClient) {
this.databaseClient = databaseClient;
}
// ...
public Flux<Map<String, Object>> someMethod() {
return this.databaseClient.sql("select * from user").fetch().all();
}
}
import org.springframework.r2dbc.core.DatabaseClient
import org.springframework.stereotype.Component
import reactor.core.publisher.Flux
@Component
class MyBean(private val databaseClient: DatabaseClient) {
// ...
fun someMethod(): Flux<Map<String, Any>> {
return databaseClient.sql("select * from user").fetch().all()
}
}
Spring Data R2DBC 仓库
Spring Data 的 R2DBC 仓库是你可以定义用于访问数据的接口。
查询是从你的方法名称自动生成的。
例如,一个城市仓库接口可能会声明一个findAllByState(字符串状态)寻找给定州内所有城市的方法。
对于更复杂的查询,你可以用 Spring Data 的注释来标记你的方法@Query注解。
以下示例展示了典型的 Spring Data 存储库接口定义:
-
Java
-
Kotlin
import reactor.core.publisher.Mono;
import org.springframework.data.repository.Repository;
public interface CityRepository extends Repository<City, Long> {
Mono<City> findByNameAndStateAllIgnoringCase(String name, String state);
}
import org.springframework.data.repository.Repository
import reactor.core.publisher.Mono
interface CityRepository : Repository<City, Long> {
fun findByNameAndStateAllIgnoringCase(name: String, state: String): Mono<City>
}
| 我们刚刚触及了Spring Data R2DBC的表面。完整详情请参见 Spring Data R2DBC 参考文档。 |