Spring Boot は、SQL と NoSQL の両方の多くのデータテクノロジーと統合されています。

1. SQL データベース

Spring Framework は、JdbcClient または JdbcTemplate を使用した直接 JDBC アクセスから、Hibernate などの完全な「オブジェクトリレーショナルマッピング」テクノロジに至るまで、SQL データベースを操作するための広範なサポートを提供します。Spring Data は、追加レベルの機能を提供します。つまり、インターフェースから Repository 実装を直接作成し、規約を使用してメソッド名からクエリを生成します。

1.1. DataSource を構成する

Java の javax.sql.DataSource インターフェースは、データベース接続を操作する標準的な方法を提供します。従来、DataSource は URL といくつかの資格情報を使用して、データベース接続を確立します。

通常、DataSource の構成を完全に制御するためのより高度な例については、「方法」セクションを参照してください。

1.1.1. 組み込みデータベースのサポート

インメモリ埋め込みデータベースを使用してアプリケーションを開発すると便利な場合がよくあります。明らかに、インメモリデータベースは永続的なストレージを提供しません。アプリケーションの起動時にデータベースにデータを入力し、アプリケーションの終了時にデータを破棄する準備をする必要があります。

「使い方」セクションには、データベースの初期化方法に関するセクションが含まれています

Spring Boot は、組み込み H2 (英語) HSQL (英語) Derby [Apache] (英語) データベースを自動構成できます。接続 URL を指定する必要はありません。使用する組み込みデータベースへのビルド依存関係を含めるだけで済みます。クラスパスに複数の組み込みデータベースがある場合は、spring.datasource.embedded-database-connection 構成プロパティを設定して、どれを使用するかを制御します。プロパティを none に設定すると、組み込みデータベースの自動構成が無効になります。

テストでこの機能を使用している場合、使用するアプリケーションコンテキストの数に関係なく、テストスイート全体で同じデータベースが再利用されることに気付く場合があります。各コンテキストに個別の組み込みデータベースがあることを確認する場合は、spring.datasource.generate-unique-name を true に設定する必要があります。

例: 典型的な 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>
組み込みデータベースを自動構成するには、spring-jdbc に依存する必要があります。この例では、spring-boot-starter-data-jpa を介して推移的にプルされます。
何らかの理由で埋め込みデータベースの接続 URL を構成する場合は、データベースの自動シャットダウンが無効になっていることを確認してください。H2 を使用する場合は、DB_CLOSE_ON_EXIT=FALSE を使用する必要があります。HSQLDB を使用する場合は、shutdown=true が使用されていないことを確認する必要があります。データベースの自動シャットダウンを無効にすると、Spring Boot がデータベースを閉じるタイミングを制御できるため、データベースへのアクセスが不要になったときに確実に実行されます。

1.1.2. 本番データベースへの接続

本番データベース接続は、プーリング DataSource を使用して自動構成することもできます。

1.1.3. DataSource の設定

DataSource 構成は、spring.datasource.*外部構成プロパティによって制御されます。例: application.properties で次のセクションを宣言できます。

Properties
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
Yaml
spring:
  datasource:
    url: "jdbc:mysql://localhost/test"
    username: "dbuser"
    password: "dbpass"
spring.datasource.url プロパティを設定して、少なくとも URL を指定する必要があります。そうでない場合、Spring Boot は組み込みデータベースの自動構成を試みます。
Spring Boot は、ほとんどのデータベースの JDBC ドライバークラスを URL から推測できます。特定のクラスを指定する必要がある場合は、spring.datasource.driver-class-name プロパティを使用できます。
プーリング DataSource を作成するには、有効な Driver クラスが利用可能であることを確認できる必要があるため、何かを行う前にそれを確認します。つまり、spring.datasource.driver-class-name=com.mysql.jdbc.Driver を設定する場合、そのクラスはロード可能でなければなりません。

サポートされているオプションの詳細については、DataSourceProperties [GitHub] (英語) を参照してください。これらは、実際の実装に関係なく機能する標準オプションです。それぞれのプレフィックス(spring.datasource.hikari.*spring.datasource.tomcat.*spring.datasource.dbcp2.*spring.datasource.oracleucp.*)を使用して、実装固有の設定を微調整することもできます。詳細については、使用している接続プールの実装のドキュメントを参照してください。

たとえば、Tomcat 接続プール [Apache] (英語) を使用する場合、次の例に示すように、多くの追加設定をカスタマイズできます。

Properties
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.test-on-borrow=true
Yaml
spring:
  datasource:
    tomcat:
      max-wait: 10000
      max-active: 50
      test-on-borrow: true

これにより、使用可能な接続がない場合に例外をスローする前に 10000 ミリ秒待機するようにプールが設定され、接続の最大数が 50 に制限され、プールから借用する前に接続が検証されます。

1.1.4. サポートされている接続プール

Spring Boot は、特定の実装を選択するために次のアルゴリズムを使用します。

  1. パフォーマンスと同時実行性の点から、HikariCP [GitHub] (英語) をお勧めします。HikariCP が使用可能な場合、常に選択します。

  2. それ以外の場合、Tomcat プーリング DataSource が利用可能であれば、それを使用します。

  3. それ以外の場合、Commons DBCP2 [Apache] (英語) が利用可能な場合は、それを使用します。

  4. HikariCP、Tomcat、DBCP2 のいずれも使用できない場合、Oracle UCP が使用可能な場合は、それを使用します。

spring-boot-starter-jdbc または spring-boot-starter-data-jpa の「スターター」を使用する場合、HikariCP への依存関係が自動的に取得されます。

spring.datasource.type プロパティを設定することにより、そのアルゴリズムを完全にバイパスし、使用する接続プールを指定できます。tomcat-jdbc はデフォルトで提供されているため、これは Tomcat コンテナーでアプリケーションを実行する場合に特に重要です。

追加の接続プールは、DataSourceBuilder を使用していつでも手動で構成できます。独自の DataSource Bean を定義する場合、自動構成は行われません。次の接続プールは DataSourceBuilder でサポートされています。

  • HikariCP

  • Tomcat プーリング Datasource

  • Commons DBCP2

  • Oracle UCP& OracleDataSource

  • Spring Framework の SimpleDriverDataSource

  • H2 JdbcDataSource

  • PostgreSQL PGSimpleDataSource

  • C3P0

1.1.5. JNDI DataSource への接続

Spring Boot アプリケーションをアプリケーションサーバーにデプロイする場合、アプリケーションサーバーの組み込み機能を使用して DataSource を構成および管理し、JNDI を使用してそれにアクセスすることができます。

spring.datasource.jndi-name プロパティは、spring.datasource.urlspring.datasource.usernamespring.datasource.password プロパティの代わりに使用して、特定の JNDI ロケーションから DataSource にアクセスできます。例: application.properties の次のセクションは、JBoss AS で定義された DataSource にアクセスする方法を示しています。

Properties
spring.datasource.jndi-name=java:jboss/datasources/customers
Yaml
spring:
  datasource:
    jndi-name: "java:jboss/datasources/customers"

1.2. JdbcTemplate の使用

Spring の JdbcTemplate および NamedParameterJdbcTemplate クラスは自動構成されており、次の例に示すように、独自の Bean に直接 @Autowire できます。

Java
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 ...
    }

}
Kotlin
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
spring.jdbc.template.max-rows=500
Yaml
spring:
  jdbc:
    template:
      max-rows: 500
NamedParameterJdbcTemplate は、バックグラウンドで同じ JdbcTemplate インスタンスを再利用します。複数の JdbcTemplate が定義されていて、1 次候補が存在しない場合、NamedParameterJdbcTemplate は自動構成されません。

1.3. JdbcClient の使用

Spring の JdbcClient は、NamedParameterJdbcTemplate の存在に基づいて自動構成されます。次の例に示すように、独自の Bean に直接注入することもできます。

Java
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 ...
    }

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

}

自動構成を利用して基礎となる JdbcTemplate を作成する場合、spring.jdbc.template.* プロパティを使用したカスタマイズはクライアントでも同様に考慮されます。

1.4. JPA および Spring Data JPA

Java Persistence API は、オブジェクトをリレーショナルデータベースに「マップ」できる標準テクノロジーです。spring-boot-starter-data-jpa POM を使用すると、簡単に開始できます。以下の重要な依存関係を提供します。

  • Hibernate: 最も一般的な JPA 実装の 1 つ。

  • Spring Data JPA: JPA ベースのリポジトリの実装に役立ちます。

  • Spring ORM: Spring Framework からのコア ORM サポート。

ここでは、JPA または Spring Data の詳細については詳しく説明しません。spring.io“JPA でデータアクセス” ガイドに従い、Spring Data JPA および Hibernate (英語) のリファレンスドキュメントを読むことができます。

1.4.1. エンティティクラス

従来、JPA「エンティティ」クラスは persistence.xml ファイルで指定されていました。Spring Boot では、このファイルは必要なく、代わりに "Entity Scanning" が使用されます。デフォルトでは、自動構成パッケージがスキャンされます。

@Entity@Embeddable@MappedSuperclass でアノテーションが付けられたクラスはすべて考慮されます。一般的なエンティティクラスは、次の例のようになります。

Java
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

}
Kotlin
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 アノテーションを使用して、エンティティスキャンの場所をカスタマイズできます。"howto.html" 使い方を参照してください。

1.4.2. Spring Data JPA リポジトリ

Spring Data JPA リポジトリは、データにアクセスするために定義できるインターフェースです。JPA クエリは、メソッド名から自動的に作成されます。例: CityRepository インターフェースは、特定の状態のすべての都市を見つけるために findAllByState(String state) メソッドを宣言する場合があります。

より複雑なクエリの場合、Spring Data の Query (Javadoc) アノテーションでメソッドにアノテーションを付けることができます。

Spring Data リポジトリは通常、Repository (Javadoc) または CrudRepository (Javadoc) インターフェースから拡張されます。自動構成を使用する場合、自動構成パッケージでリポジトリが検索されます。

@EnableJpaRepositories を使用して、リポジトリを探す場所をカスタマイズできます。

次の例は、典型的な Spring Data リポジトリインターフェース定義を示しています。

Java
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);

}
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

interface CityRepository : Repository<City?, Long?> {

    fun findAll(pageable: Pageable?): Page<City?>?

    fun findByNameAndStateAllIgnoringCase(name: String?, state: String?): City?

}

Spring Data JPA リポジトリは、3 つの異なるブートストラップモードをサポートしています: デフォルト、遅延、レイジー。遅延または遅延ブートストラップを有効にするには、spring.data.jpa.repositories.bootstrap-mode プロパティをそれぞれ deferred または lazy に設定します。遅延または遅延ブートストラップを使用する場合、自動構成された EntityManagerFactoryBuilder は、コンテキストの AsyncTaskExecutor をブートストラップエグゼキューターとして使用します(存在する場合)。複数存在する場合は、applicationTaskExecutor という名前が使用されます。

遅延または遅延ブートストラップを使用する場合は、アプリケーションコンテキストのブートストラップフェーズの後で、JPA インフラストラクチャへのアクセスを必ず遅延させてください。SmartInitializingSingleton を使用して、JPA インフラストラクチャを必要とする初期化を呼び出すことができます。Spring Bean として作成される JPA コンポーネント(コンバーターなど)の場合、依存関係がある場合は、ObjectProvider を使用して依存関係の解決を遅らせます。

Spring Data JPA に関して、ほんの少し触れただけです。詳細については、Spring Data JPA リファレンスドキュメントを参照してください。

1.4.3. Spring Data Envers リポジトリ

Spring Data Envers が使用可能な場合、JPA リポジトリは、一般的な Envers クエリをサポートするように自動構成されます。

Spring Data Envers を使用するには、次の例に示すように、リポジトリが RevisionRepository から拡張されていることを確認してください。

Java
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);

}
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

interface CountryRepository :
        RevisionRepository<Country?, Long?, Int>,
        Repository<Country?, Long?> {

    fun findAll(pageable: Pageable?): Page<Country?>?

}
詳細については、Spring Data Envers リファレンスドキュメントを確認してください。

1.4.4. JPA データベースの作成と削除

デフォルトでは、組み込みデータベース(H2、HSQL、Derby)を使用する場合にのみ、JPA データベースが自動的に作成されます。spring.jpa.* プロパティを使用して、JPA 設定を明示的に構成できます。例: テーブルを作成および削除するには、次の行を application.properties に追加します。

Properties
spring.jpa.hibernate.ddl-auto=create-drop
Yaml
spring:
  jpa:
    hibernate.ddl-auto: "create-drop"
Hibernate の独自の内部プロパティ名(覚えている場合)は hibernate.hbm2ddl.auto です。spring.jpa.properties.* を使用して、他の Hibernate ネイティブプロパティとともに設定できます(プレフィックスは、エンティティマネージャーに追加する前に削除されます)。次の行は、Hibernate の JPA プロパティの設定例を示しています。
Properties
spring.jpa.properties.hibernate[globally_quoted_identifiers]=true
Yaml
spring:
  jpa:
    properties:
      hibernate:
        "globally_quoted_identifiers": "true"

上記の例の行は、hibernate.globally_quoted_identifiers プロパティの true の値を Hibernate エンティティマネージャーに渡します。

デフォルトでは、DDL の実行 (または検証) は ApplicationContext が開始するまで延期されます。

1.4.5. Open EntityManager in View

Web アプリケーションを実行している場合、Spring Boot はデフォルトで OpenEntityManagerInViewInterceptor (Javadoc) を登録して "Open EntityManager in View" パターンを適用し、Web ビューでの遅延読み込みを可能にします。この動作が望ましくない場合は、application.properties で spring.jpa.open-in-view を false に設定する必要があります。

1.5. Spring Data JDBC

Spring Data には JDBC のリポジトリサポートが含まれており、CrudRepository のメソッドの SQL を自動的に生成します。より高度なクエリのために、@Query アノテーションが提供されています。

必要な依存関係がクラスパスにある場合、Spring Boot は Spring Data の JDBC リポジトリを自動構成します。それらは、spring-boot-starter-data-jdbc への単一の依存関係でプロジェクトに追加できます。必要に応じて、@EnableJdbcRepositories アノテーションまたは AbstractJdbcConfiguration サブクラスをアプリケーションに追加することで、Spring Data JDBC の構成を制御できます。

Spring Data JDBC の詳細については、リファレンスドキュメントを参照してください。

1.6. H2 の Web コンソールを使用する

H2 データベース (英語) は、Spring Boot が自動構成できるブラウザーベースのコンソール (英語) を提供します。コンソールは、次の条件が満たされると自動構成されます。

  • サーブレットベースの Web アプリケーションを開発しています。

  • com.h2database:h2 はクラスパス上にあります。

  • Spring Boot の開発者ツールを使用しています。

Spring Boot の開発者ツールを使用していないが、H2 のコンソールを引き続き使用したい場合は、spring.h2.console.enabled プロパティを true の値で構成できます。
H2 コンソールは開発中の使用のみを目的としているため、spring.h2.console.enabled が本番環境で true に設定されないように注意する必要があります。

1.6.1. H2 コンソールのパスを変更する

デフォルトでは、コンソールは /h2-console で使用可能です。spring.h2.console.path プロパティを使用して、コンソールのパスをカスタマイズできます。

1.6.2. 安全なアプリケーションでの H2 コンソールへのアクセス

H2 Console はフレームを使用し、開発のみを目的としているため、CSRF 保護対策を実装していません。アプリケーションで Spring Security を使用する場合は、次のように構成する必要があります。

  • コンソールに対するリクエストの CSRF 保護を無効にします。

  • コンソールからのレスポンスでヘッダー X-Frame-Options を SAMEORIGIN に設定します。

CSRF およびヘッダー X-Frame-Options の詳細については、Spring Security リファレンスガイドを参照してください。

簡単なセットアップでは、次のような SecurityFilterChain を使用できます。

Java
import org.springframework.boot.autoconfigure.security.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.web.SecurityFilterChain;

@Profile("dev")
@Configuration(proxyBeanMethods = false)
public class DevProfileSecurityConfiguration {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher(PathRequest.toH2Console());
        http.authorizeHttpRequests(yourCustomAuthorization());
        http.csrf((csrf) -> csrf.disable());
        http.headers((headers) -> headers.frameOptions((frame) -> frame.sameOrigin()));
        return http.build();
    }


}
Kotlin
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 保護を無効にするか、Web サイトのフレームを許可すると、重大なセキュリティリスクが発生する可能性があります。
PathRequest.toH2Console() は、コンソールのパスがカスタマイズされている場合にも、正しいリクエストマッチャーを返します。

1.7. jOOQ を使用する

jOOQ オブジェクト指向クエリ(jOOQ (英語) )は、データベースから Java コードを生成し、その流れるような API を介して型安全な SQL クエリを作成できる Data Geekery (英語) の人気製品です。Spring Boot では、有償版とオープンソース版の両方を使用できます。

1.7.1. コード生成

jOOQ 型安全クエリを使用するには、データベーススキーマから Java クラスを生成する必要があります。jOOQ ユーザーマニュアル (英語) の指示に従うことができます。jooq-codegen-maven プラグインを使用し、spring-boot-starter-parent 「親 POM」も使用する場合、プラグインの <version> タグを安全に省略できます。SpringBoot 定義バージョン変数(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>

1.7.2. DSLContext を使用する

jOOQ によって提供される流れるような API は、org.jooq.DSLContext インターフェースを介して開始されます。Spring Boot は、DSLContext を Spring Bean として自動構成し、それをアプリケーション DataSource に接続します。DSLContext を使用するには、次の例に示すように、DSLContext を注入できます。

Java
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;
    }


}
Kotlin
import org.jooq.DSLContext
import org.springframework.stereotype.Component
import java.util.GregorianCalendar

@Component
class MyBean(private val create: DSLContext) {


}
jOOQ マニュアルでは、create という名前の変数を使用して DSLContext を保持する傾向があります。

その後、次の例に示すように、DSLContext を使用してクエリを作成できます。

Java
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);
Kotlin
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)
}

1.7.3. jOOQ SQL ダイアレクト

spring.jooq.sql-dialect プロパティが設定されていない限り、Spring Boot はデータソースに使用する SQL ダイアレクトを決定します。Spring Boot がダイアレクトを検出できなかった場合、DEFAULT を使用します。

Spring Boot は、jOOQ のオープンソースバージョンでサポートされているダイアレクトのみを自動構成できます。

1.7.4. jOOQ のカスタマイズ

org.jooq.Configuration@Bean を作成する前に呼び出される、独自の DefaultConfigurationCustomizer Bean を定義することにより、より高度なカスタマイズを実現できます。これは、自動構成によって適用されるものよりも優先されます。

jOOQ 構成を完全に制御したい場合は、独自の org.jooq.Configuration@Bean を作成することもできます。

1.8. R2DBC を使用する

リアクティブリレーショナルデータベース接続(R2DBC (英語) )プロジェクトは、リアクティブプログラミング API をリレーショナルデータベースにもたらします。R2DBC の io.r2dbc.spi.Connection は、ノンブロッキングデータベース接続を操作する標準的な方法を提供します。接続は、jdbc を使用した DataSource と同様に、ConnectionFactory を使用して提供されます。

ConnectionFactory 構成は、spring.r2dbc.* の外部構成プロパティによって制御されます。例: application.properties で次のセクションを宣言できます。

Properties
spring.r2dbc.url=r2dbc:postgresql://localhost/test
spring.r2dbc.username=dbuser
spring.r2dbc.password=dbpass
Yaml
spring:
  r2dbc:
    url: "r2dbc:postgresql://localhost/test"
    username: "dbuser"
    password: "dbpass"
Spring Boot は R2DBC の接続ファクトリディスカバリからドライバーを取得するため、ドライバークラス名を指定する必要はありません。
少なくとも URL を指定する必要があります。URL で指定された情報は、個々のプロパティ、つまり nameusernamepassword およびプーリングオプションよりも優先されます。
「使い方」セクションには、データベースの初期化方法に関するセクションが含まれています

ConnectionFactory によって作成された接続をカスタマイズするには、つまり、主要データベース構成で構成したくない (または構成できない) 特定のパラメーターを設定するには、ConnectionFactoryOptionsBuilderCustomizer@Bean を使用できます。次の例は、残りのオプションをアプリケーション構成から取得しながら、データベースポートを手動でオーバーライドする方法を示しています。

Java
import io.r2dbc.spi.ConnectionFactoryOptions;

import org.springframework.boot.autoconfigure.r2dbc.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);
    }

}
Kotlin
import io.r2dbc.spi.ConnectionFactoryOptions
import org.springframework.boot.autoconfigure.r2dbc.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
import java.util.HashMap;
import java.util.Map;

import io.r2dbc.postgresql.PostgresqlConnectionFactoryProvider;

import org.springframework.boot.autoconfigure.r2dbc.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);
    }

}
Kotlin
import io.r2dbc.postgresql.PostgresqlConnectionFactoryProvider
import org.springframework.boot.autoconfigure.r2dbc.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)
        }
    }

}

ConnectionFactory Bean が使用可能な場合、通常の JDBC DataSource 自動構成がバックオフします。JDBC DataSource 自動構成を保持する必要があり、リアクティブアプリケーションでブロッキング JDBC API を使用するリスクに満足している場合は、アプリケーションの @Configuration クラスに @Import(DataSourceAutoConfiguration.class) を追加して再度有効にします。

1.8.1. 組み込みデータベースのサポート

JDBC サポートと同様に、Spring Boot はリアクティブ使用のために組み込みデータベースを自動的に構成できます。接続 URL を提供する必要はありません。次の例に示すように、使用する組み込みデータベースへのビルド依存関係のみを含める必要があります。

<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-h2</artifactId>
    <scope>runtime</scope>
</dependency>

テストでこの機能を使用している場合、使用するアプリケーションコンテキストの数に関係なく、テストスイート全体で同じデータベースが再利用されることに気付く場合があります。各コンテキストに個別の組み込みデータベースがあることを確認する場合は、spring.r2dbc.generate-unique-name を true に設定する必要があります。

1.8.2. DatabaseClient の使用

DatabaseClient Bean は自動構成されており、次の例に示すように、@Autowire を独自の Bean に直接組み込むことができます。

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

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

}

1.8.3. Spring Data R2DBC リポジトリ

Spring Data R2DBC リポジトリは、データにアクセスするために定義できるインターフェースです。クエリはメソッド名から自動的に作成されます。例: CityRepository インターフェースは、特定の状態のすべての都市を見つけるために findAllByState(String state) メソッドを宣言できます。

より複雑なクエリの場合、Spring Data の Query (Javadoc) アノテーションでメソッドにアノテーションを付けることができます。

Spring Data リポジトリは通常、Repository (Javadoc) または CrudRepository (Javadoc) インターフェースから拡張されます。自動構成を使用する場合、自動構成パッケージでリポジトリが検索されます。

次の例は、典型的な Spring Data リポジトリインターフェース定義を示しています。

Java
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);

}
Kotlin
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 リファレンスドキュメントを参照してください。

2. NoSQL テクノロジーの使用

Spring Data は、次のようなさまざまな NoSQL テクノロジーへのアクセスに役立つ追加プロジェクトを提供します。

これらのうち、Spring Boot は、Cassandra、Couchbase、Elasticsearch、LDAP、MongoDB、Neo4J、Redis の自動構成を提供します。さらに、Apache Geode 用 Spring Boot [GitHub] (英語) は、Apache Geode の自動構成を提供します。他のプロジェクトを利用することもできますが、自分で構成する必要があります。spring.io/projects/spring-data の適切なリファレンスドキュメントを参照してください。

Spring Boot は InfluxDB クライアントの自動構成も提供しますが、独自の Spring Boot 統合を提供する新しい InfluxDB Java クライアント [GitHub] (英語) を優先して非推奨になりました。

2.1. Redis

Redis (英語) は、キャッシュ、メッセージブローカー、豊富な機能を備えたキーと値のストアです。Spring Boot は、Lettuce [GitHub] (英語) および Jedis [GitHub] (英語) クライアントライブラリの基本的な自動構成と、Spring Data Redis [GitHub] (英語) が提供する抽象化を提供します。

依存関係を便利な方法で収集するための spring-boot-starter-data-redis 「スターター」があります。デフォルトでは、Lettuce [GitHub] (英語) を使用します。そのスターターは、従来のアプリケーションとリアクティブアプリケーションの両方を処理します。

また、リアクティブサポートを備えた他のストアとの一貫性を保つために、spring-boot-starter-data-redis-reactive 「スターター」も提供しています。

2.1.1. Redis への接続

他の Spring Bean と同様に、自動構成された RedisConnectionFactoryStringRedisTemplate、またはバニラ RedisTemplate インスタンスを注入できます。次のリストは、そのような Bean の例を示しています。

Java
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final StringRedisTemplate template;

    public MyBean(StringRedisTemplate template) {
        this.template = template;
    }

    // ...

    public Boolean someMethod() {
        return this.template.hasKey("spring");
    }

}
Kotlin
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.stereotype.Component

@Component
class MyBean(private val template: StringRedisTemplate) {

    // ...

    fun someMethod(): Boolean {
        return template.hasKey("spring")
    }

}

デフォルトでは、インスタンスは localhost:6379 で Redis サーバーへの接続を試みます。次の例に示すように、spring.data.redis.* プロパティを使用してカスタム接続の詳細を指定できます。

Properties
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.database=0
spring.data.redis.username=user
spring.data.redis.password=secret
Yaml
spring:
  data:
    redis:
      host: "localhost"
      port: 6379
      database: 0
      username: "user"
      password: "secret"
より高度なカスタマイズのために、LettuceClientConfigurationBuilderCustomizer を実装する任意の数の Bean を登録することもできます。ClientResources は、ClientResourcesBuilderCustomizer を使用してカスタマイズすることもできます。Jedis を使用している場合は、JedisClientConfigurationBuilderCustomizer も利用できます。または、型 RedisStandaloneConfigurationRedisSentinelConfigurationRedisClusterConfiguration の Bean を登録して、構成を完全に制御することもできます。

自動構成された型の独自の @Bean を追加すると、デフォルトが置き換えられます (除外がその型ではなく Bean 名、redisTemplate に基づいている場合の RedisTemplate の場合を除きます)。

デフォルトでは、commons-pool2 がクラスパス上にある場合、プールされた接続ファクトリは自動構成されます。

自動構成された RedisConnectionFactory は、次の例に示すようにプロパティを設定することで、サーバーとの通信に SSL を使用するように構成できます。

Properties
spring.data.redis.ssl.enabled=true
Yaml
spring:
  data:
    redis:
      ssl:
        enabled: true

次の例に示すように、カスタム SSL トラストマテリアルを SSL バンドルで構成し、RedisConnectionFactory に適用できます。

Properties
spring.data.redis.ssl.bundle=example
Yaml
spring:
  data:
    redis:
      ssl:
        bundle: "example"

2.2. MongoDB

MongoDB (英語) は、従来のテーブルベースのリレーショナルデータの代わりに JSON のようなスキーマを使用するオープンソースの NoSQL ドキュメントデータベースです。Spring Boot は、spring-boot-starter-data-mongodb および spring-boot-starter-data-mongodb-reactive 「スターター」など、MongoDB を操作するためのいくつかの便利な機能を提供します。

2.2.1. MongoDB データベースへの接続

MongoDB データベースにアクセスするために、自動構成された org.springframework.data.mongodb.MongoDatabaseFactory を注入できます。デフォルトでは、インスタンスは mongodb://localhost/test で MongoDB サーバーへの接続を試みます。次の例は、MongoDB データベースに接続する方法を示しています。

Java
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final MongoDatabaseFactory mongo;

    public MyBean(MongoDatabaseFactory mongo) {
        this.mongo = mongo;
    }

    // ...

    public MongoCollection<Document> someMethod() {
        MongoDatabase db = this.mongo.getMongoDatabase();
        return db.getCollection("users");
    }

}
Kotlin
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.springframework.data.mongodb.MongoDatabaseFactory
import org.springframework.stereotype.Component

@Component
class MyBean(private val mongo: MongoDatabaseFactory) {

    // ...

    fun someMethod(): MongoCollection<Document> {
        val db = mongo.mongoDatabase
        return db.getCollection("users")
    }

}

独自の MongoClient を定義している場合、それを使用して適切な MongoDatabaseFactory を自動構成します。

自動構成された MongoClient は、MongoClientSettings Bean を使用して作成されます。独自の MongoClientSettings を定義した場合、変更なしで使用され、spring.data.mongodb プロパティは無視されます。それ以外の場合、MongoClientSettings は自動構成され、spring.data.mongodb プロパティが適用されます。いずれの場合も、1 つ以上の MongoClientSettingsBuilderCustomizer Bean を宣言して、MongoClientSettings 構成を微調整できます。それぞれは、MongoClientSettings の構築に使用される MongoClientSettings.Builder で順番に呼び出されます。

次の例に示すように、spring.data.mongodb.uri プロパティを設定して URL を変更し、レプリカセットなどの追加設定を構成できます。

Properties
spring.data.mongodb.uri=mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test
Yaml
spring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test"

または、個別のプロパティを使用して接続の詳細を指定できます。例: application.properties で次の設定を宣言できます。

Properties
spring.data.mongodb.host=mongoserver1.example.com
spring.data.mongodb.port=27017
spring.data.mongodb.additional-hosts[0]=mongoserver2.example.com:23456
spring.data.mongodb.database=test
spring.data.mongodb.username=user
spring.data.mongodb.password=secret
Yaml
spring:
  data:
    mongodb:
      host: "mongoserver1.example.com"
      port: 27017
      additional-hosts:
      - "mongoserver2.example.com:23456"
      database: "test"
      username: "user"
      password: "secret"

自動構成された MongoClient は、次の例に示すようにプロパティを設定することで、サーバーとの通信に SSL を使用するように構成できます。

Properties
spring.data.mongodb.uri=mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test
spring.data.mongodb.ssl.enabled=true
Yaml
spring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test"
      ssl:
        enabled: true

次の例に示すように、カスタム SSL トラストマテリアルを SSL バンドルで構成し、MongoClient に適用できます。

Properties
spring.data.mongodb.uri=mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test
spring.data.mongodb.ssl.bundle=example
Yaml
spring:
  data:
    mongodb:
      uri: "mongodb://user:[email protected] (英語)  :27017,mongoserver2.example.com:23456/test"
      ssl:
        bundle: "example"

spring.data.mongodb.port が指定されていない場合、デフォルトの 27017 が使用されます。前に示した例からこの行を削除できます。

host:port 構文を使用して、ポートをホストアドレスの一部として指定することもできます。additional-hosts エントリのポートを変更する必要がある場合は、この形式を使用する必要があります。

Spring Data MongoDB を使用しない場合は、MongoDatabaseFactory を使用する代わりに MongoClient Bean を注入できます。MongoDB 接続の確立を完全に制御したい場合は、独自の MongoDatabaseFactory または MongoClient Bean を宣言することもできます。
リアクティブドライバーを使用している場合、SSL には Netty が必要です。Netty が使用可能であり、使用するファクトリがまだカスタマイズされていない場合、自動構成によってこのファクトリが自動的に構成されます。

2.2.2. MongoTemplate

Spring Data MongoDB は、その設計が Spring の JdbcTemplate に非常に似ている MongoTemplate (Javadoc) クラスを提供します。JdbcTemplate と同様に、Spring Boot は、次のように、テンプレートをインジェクトするために Bean を自動構成します。

Java
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final MongoTemplate mongoTemplate;

    public MyBean(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    // ...

    public MongoCollection<Document> someMethod() {
        return this.mongoTemplate.getCollection("users");
    }

}
Kotlin
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.stereotype.Component

@Component
class MyBean(private val mongoTemplate: MongoTemplate) {

    // ...

    fun someMethod(): MongoCollection<Document> {
        return mongoTemplate.getCollection("users")
    }

}

詳細については、MongoOperations Javadoc を参照してください。

2.2.3. Spring Data MongoDB リポジトリ

Spring Data には、MongoDB のリポジトリサポートが含まれています。前述の JPA リポジトリと同様に、基本的な原則は、クエリがメソッド名に基づいて自動的に構築されることです。

実際、Spring Data JPA と Spring Data MongoDB はどちらも同じ共通インフラストラクチャを共有しています。以前の JPA の例をとることができ、City が JPA @Entity ではなく MongoDB データクラスであると仮定すると、次の例に示すように、同じように機能します。

Java
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);

}
Kotlin
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?
}

リポジトリとドキュメントはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableMongoRepositories と @EntityScan をそれぞれ使用して、リポジトリとドキュメントを検索する場所をカスタマイズできます。

豊富なオブジェクトマッピングテクノロジを含む Spring Data MongoDB の詳細については、リファレンスドキュメントを参照してください。

2.3. Neo4j

Neo4j (英語) は、ファーストクラスの関連で接続されたノードのリッチデータモデルを使用するオープンソースの NoSQL グラフデータベースであり、従来の RDBMS アプローチよりも接続されたビッグデータに適しています。Spring Boot は、spring-boot-starter-data-neo4j 「スターター」など、Neo4j での作業にいくつかの便利な機能を提供します。

2.3.1. Neo4j データベースへの接続

Neo4j サーバーにアクセスするには、自動構成された org.neo4j.driver.Driver を挿入できます。デフォルトでは、インスタンスは Bolt プロトコルを使用して localhost:7687 で Neo4j サーバーに接続しようとします。次の例は、とりわけ Session へのアクセスを提供する Neo4j Driver を注入する方法を示しています。

Java
import org.neo4j.driver.Driver;
import org.neo4j.driver.Session;
import org.neo4j.driver.Values;

import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final Driver driver;

    public MyBean(Driver driver) {
        this.driver = driver;
    }

    // ...

    public String someMethod(String message) {
        try (Session session = this.driver.session()) {
            return session.executeWrite(
                    (transaction) -> transaction
                        .run("CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)",
                                Values.parameters("message", message))
                        .single()
                        .get(0)
                        .asString());
        }
    }

}
Kotlin
import org.neo4j.driver.*
import org.springframework.stereotype.Component

@Component
class MyBean(private val driver: Driver) {

    // ...

    fun someMethod(message: String?): String {
        driver.session().use { session ->
            return@someMethod session.executeWrite { transaction: TransactionContext ->
                transaction
                    .run(
                        "CREATE (a:Greeting) SET a.message = \$message RETURN a.message + ', from node ' + id(a)",
                        Values.parameters("message", message)
                    )
                    .single()[0].asString()
            }
        }
    }

}

spring.neo4j.* プロパティを使用して、ドライバーのさまざまなアスペクトを構成できます。次の例は、使用する URI と資格情報を構成する方法を示しています。

Properties
spring.neo4j.uri=bolt://my-server:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secret
Yaml
spring:
  neo4j:
    uri: "bolt://my-server:7687"
    authentication:
      username: "neo4j"
      password: "secret"

自動構成された Driver は、ConfigBuilder を使用して作成されます。構成を微調整するには、1 つ以上の ConfigBuilderCustomizer Bean を宣言します。Driver をビルドするために使用される ConfigBuilder で順番に呼び出されます。

2.3.2. Spring Data Neo4j リポジトリ

Spring Data には、Neo4j のリポジトリサポートが含まれています。Spring Data Neo4j の詳細については、リファレンスドキュメントを参照してください。

Spring Data Neo4j は、他の多くの Spring Data モジュールと同様に、Spring Data JPA と共通のインフラストラクチャを共有します。前の JPA の例を使用して、City を JPA @Entity ではなく Spring Data Neo4j @Node として定義すると、リポジトリの抽象化は次の例に示すように同じように機能します。

Java
import java.util.Optional;

import org.springframework.data.neo4j.repository.Neo4jRepository;

public interface CityRepository extends Neo4jRepository<City, Long> {

    Optional<City> findOneByNameAndState(String name, String state);

}
Kotlin
import org.springframework.data.neo4j.repository.Neo4jRepository
import java.util.Optional

interface CityRepository : Neo4jRepository<City?, Long?> {

    fun findOneByNameAndState(name: String?, state: String?): Optional<City?>?

}

spring-boot-starter-data-neo4j の「スターター」は、リポジトリのサポートとトランザクション管理を可能にします。Spring Boot は、Neo4jTemplate または ReactiveNeo4jTemplate Bean を使用して、クラシックリポジトリとリアクティブ Neo4j リポジトリの両方をサポートします。プロジェクト Reactor がクラスパスで使用可能な場合、リアクティブスタイルも自動構成されます。

リポジトリとエンティティはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableNeo4jRepositories と @EntityScan をそれぞれ使用して、リポジトリとエンティティを検索する場所をカスタマイズできます。

リアクティブスタイルを使用するアプリケーションでは、ReactiveTransactionManager は自動構成されません。トランザクション管理を有効にするには、構成で次の Bean を定義する必要があります。

Java
import org.neo4j.driver.Driver;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider;
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager;

@Configuration(proxyBeanMethods = false)
public class MyNeo4jConfiguration {

    @Bean
    public ReactiveNeo4jTransactionManager reactiveTransactionManager(Driver driver,
            ReactiveDatabaseSelectionProvider databaseNameProvider) {
        return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
    }

}
Kotlin
import org.neo4j.driver.Driver
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.neo4j.core.ReactiveDatabaseSelectionProvider
import org.springframework.data.neo4j.core.transaction.ReactiveNeo4jTransactionManager

@Configuration(proxyBeanMethods = false)
class MyNeo4jConfiguration {

    @Bean
    fun reactiveTransactionManager(driver: Driver,
            databaseNameProvider: ReactiveDatabaseSelectionProvider): ReactiveNeo4jTransactionManager {
        return ReactiveNeo4jTransactionManager(driver, databaseNameProvider)
    }
}

2.4. Elasticsearch

Elasticsearch (英語) は、オープンソースの分散型 RESTful 検索および分析エンジンです。Spring Boot は、Elasticsearch クライアントに基本的な自動構成を提供します。

Spring Boot はいくつかのクライアントをサポートしています:

  • 公式の低レベル REST クライアント

  • 公式の Java API クライアント

  • Spring Data Elasticsearch が提供する ReactiveElasticsearchClient 

Spring Boot は、専用の「スターター」 spring-boot-starter-data-elasticsearch を提供します。

2.4.1. REST クライアントを使用した Elasticsearch への接続

Elasticsearch には、クラスターのクエリに使用できる 2 つの異なる REST クライアントが同梱されています。org.elasticsearch.client:elasticsearch-rest-client モジュールの低レベルクライアント (英語) と co.elastic.clients:elasticsearch-java モジュールの Java API クライアント (英語) です。さらに、Spring Boot は、org.springframework.data:spring-data-elasticsearch モジュールからのリアクティブクライアントのサポートを提供します。デフォルトでは、クライアントは localhost:9200 をターゲットにします。次の例に示すように、spring.elasticsearch.* プロパティを使用して、クライアントの構成方法をさらに調整できます。

Properties
spring.elasticsearch.uris=https://search.example.com:9200
spring.elasticsearch.socket-timeout=10s
spring.elasticsearch.username=user
spring.elasticsearch.password=secret
Yaml
spring:
  elasticsearch:
    uris: "https://search.example.com:9200"
    socket-timeout: "10s"
    username: "user"
    password: "secret"
RestClient を使用した Elasticsearch への接続

クラスパスに elasticsearch-rest-client がある場合、Spring Boot は RestClient Bean を自動構成して登録します。前述のプロパティに加えて、RestClient を微調整するために、より高度なカスタマイズのために RestClientBuilderCustomizer を実装する任意の数の Bean を登録できます。クライアントの構成を完全に制御するには、RestClientBuilder Bean を定義します。

さらに、elasticsearch-rest-client-sniffer がクラスパス上にある場合、Sniffer は、実行中の Elasticsearch クラスターからノードを自動的に検出して RestClient Bean に設定するように自動構成されます。次の例に示すように、Sniffer の構成方法をさらに調整できます。

Properties
spring.elasticsearch.restclient.sniffer.interval=10m
spring.elasticsearch.restclient.sniffer.delay-after-failure=30s
Yaml
spring:
  elasticsearch:
    restclient:
      sniffer:
        interval: "10m"
        delay-after-failure: "30s"
ElasticsearchClient を使用した Elasticsearch への接続

クラスパスに co.elastic.clients:elasticsearch-java がある場合、Spring Boot は ElasticsearchClient Bean を自動構成して登録します。

ElasticsearchClient は、前述の RestClient に依存するトランスポートを使用します。前述のプロパティを使用して ElasticsearchClient を構成できます。さらに、RestClientOptions Bean を定義して、トランスポートの動作をさらに制御することができます。

ReactiveElasticsearchClient を使用して Elasticsearch に接続する

Spring Data Elasticsearch は、リアクティブな方法で Elasticsearch インスタンスを照会するための ReactiveElasticsearchClient を提供しています。クラスパスに Spring Data Elasticsearch と Reactor がある場合、Spring Boot は ReactiveElasticsearchClient を自動構成して登録します。

ReactiveElasticsearchclient は、前述の RestClient に依存するトランスポートを使用します。前述のプロパティを使用して ReactiveElasticsearchClient を構成できます。さらに、RestClientOptions Bean を定義して、トランスポートの動作をさらに制御することができます。

2.4.2. Spring Data を使用して Elasticsearch に接続する

Elasticsearch に接続するには、ElasticsearchClient Bean を定義するか、Spring Boot によって自動構成するか、アプリケーションによって手動で提供する必要があります (前のセクションを参照)。この構成を使用すると、次の例に示すように、他の Spring Bean と同様に ElasticsearchTemplate を挿入できます。

Java
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final ElasticsearchTemplate template;

    public MyBean(ElasticsearchTemplate template) {
        this.template = template;
    }

    // ...

    public boolean someMethod(String id) {
        return this.template.exists(id, User.class);
    }

}
Kotlin
import org.springframework.stereotype.Component

@Component
class MyBean(private val template: org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate ) {

    // ...

    fun someMethod(id: String): Boolean {
        return template.exists(id, User::class.java)
    }

}

spring-data-elasticsearch および Reactor が存在する場合、Spring Boot は ReactiveElasticsearchClient および ReactiveElasticsearchTemplate を Bean として自動構成することもできます。これらは、他の REST クライアントと同等のリアクティブです。

2.4.3. Spring Data Elasticsearch リポジトリ

Spring Data には、Elasticsearch のリポジトリサポートが含まれています。前述の JPA リポジトリと同様に、基本的な原則は、クエリがメソッド名に基づいて自動的に構築されることです。

実際、Spring Data JPA と Spring Data Elasticsearch の両方が同じ共通インフラストラクチャを共有しています。以前の JPA の例を使用すると、City が JPA @Entity ではなく Elasticsearch @Document クラスであると仮定すると、同じように機能します。

リポジトリとドキュメントはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableElasticsearchRepositories と @EntityScan をそれぞれ使用して、リポジトリとドキュメントを検索する場所をカスタマイズできます。

Spring Data Elasticsearch の詳細については、リファレンスドキュメントを参照してください。

Spring Boot は、ElasticsearchRestTemplate または ReactiveElasticsearchTemplate Bean を使用して、クラシックおよびリアクティブの両方の Elasticsearch リポジトリをサポートします。おそらく、これらの Bean は、必要な依存関係が存在する場合、Spring Boot によって自動構成されます。

Elasticsearch リポジトリをバックアップするために独自のテンプレートを使用する場合は、"elasticsearchTemplate" という名前である限り、独自の ElasticsearchRestTemplate または ElasticsearchOperations@Bean を追加できます。同じことが ReactiveElasticsearchTemplate と ReactiveElasticsearchOperations にも当てはまり、Bean の名前は "reactiveElasticsearchTemplate" です。

次のプロパティを使用して、リポジトリのサポートを無効にすることができます。

Properties
spring.data.elasticsearch.repositories.enabled=false
Yaml
spring:
  data:
    elasticsearch:
      repositories:
        enabled: false

2.5. Cassandra

Cassandra [Apache] (英語) は、多くのコモディティサーバーで大量のデータを処理するために設計されたオープンソースの分散データベース管理システムです。Spring Boot は、Cassandra の自動構成と、Spring Data Cassandra [GitHub] (英語) が提供する抽象化を提供します。依存関係を便利な方法で収集するための spring-boot-starter-data-cassandra 「スターター」があります。

2.5.1. Cassandra への接続

他の Spring Bean と同様に、自動構成された CassandraTemplate または Cassandra CqlSession インスタンスを注入できます。spring.cassandra.* プロパティを使用して、接続をカスタマイズできます。通常、次の例に示すように、keyspace-name および contact-points に加えてローカルデータセンター名を指定します。

Properties
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1:9042,cassandrahost2:9042
spring.cassandra.local-datacenter=datacenter1
Yaml
spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1:9042,cassandrahost2:9042"
    local-datacenter: "datacenter1"

次の例に示すように、すべての連絡先でポートが同じ場合は、ショートカットを使用してホスト名のみを指定できます。

Properties
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
Yaml
spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"
これら 2 つの例は、デフォルトのポート 9042 と同じです。ポートを構成する必要がある場合は、spring.cassandra.port を使用してください。

自動構成された CqlSession は、次の例に示すようにプロパティを設定することで、サーバーとの通信に SSL を使用するように構成できます。

Properties
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
spring.cassandra.ssl.enabled=true
Yaml
spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"
    ssl:
      enabled: true

次の例に示すように、カスタム SSL トラストマテリアルを SSL バンドルで構成し、CqlSession に適用できます。

Properties
spring.cassandra.keyspace-name=mykeyspace
spring.cassandra.contact-points=cassandrahost1,cassandrahost2
spring.cassandra.local-datacenter=datacenter1
spring.cassandra.ssl.bundle=example
Yaml
spring:
  cassandra:
    keyspace-name: "mykeyspace"
    contact-points: "cassandrahost1,cassandrahost2"
    local-datacenter: "datacenter1"
    ssl:
      bundle: "example"

Cassandra ドライバーには、クラスパスのルートに application.conf をロードする独自の構成インフラストラクチャがあります。

Spring Boot はデフォルトではそのようなファイルを検索しませんが、spring.cassandra.config を使用してファイルをロードできます。プロパティが spring.cassandra.* と構成ファイルの両方に存在する場合、spring.cassandra.* の値が優先されます。

より高度なドライバーのカスタマイズについては、DriverConfigLoaderBuilderCustomizer を実装する任意の数の Bean を登録できます。CqlSession は、型 CqlSessionBuilderCustomizer の Bean を使用してカスタマイズできます。

CqlSessionBuilder を使用して複数の CqlSession Bean を作成する場合は、ビルダーが変更可能であることに注意してください。セッションごとに新しいコピーを挿入してください。

次のコードリストは、Cassandra Bean を挿入する方法を示しています。

Java
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final CassandraTemplate template;

    public MyBean(CassandraTemplate template) {
        this.template = template;
    }

    // ...

    public long someMethod() {
        return this.template.count(User.class);
    }

}
Kotlin
import org.springframework.data.cassandra.core.CassandraTemplate
import org.springframework.stereotype.Component

@Component
class MyBean(private val template: CassandraTemplate) {

    // ...

    fun someMethod(): Long {
        return template.count(User::class.java)
    }

}

型 CassandraTemplate の独自の @Bean を追加すると、デフォルトが置き換えられます。

2.5.2. Spring Data Cassandra リポジトリ

Spring Data には、Cassandra の基本的なリポジトリサポートが含まれています。現在、これは前述の JPA リポジトリよりも制限されており、@Query アノテーション付きファインダーメソッドが必要です。

リポジトリとエンティティはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableCassandraRepositories と @EntityScan をそれぞれ使用して、リポジトリとエンティティを検索する場所をカスタマイズできます。

Spring Data Cassandra の詳細については、リファレンスドキュメントを参照してください。

2.6. Couchbase

Couchbase (英語) は、対話型アプリケーション向けに最適化された、オープンソースの分散型マルチモデル NoSQL ドキュメント指向データベースです。Spring Boot は、Couchbase の自動構成と、Spring Data Couchbase [GitHub] (英語) が提供する抽象化を提供します。依存関係を便利な方法で収集するための spring-boot-starter-data-couchbase および spring-boot-starter-data-couchbase-reactive 「スターター」があります。

2.6.1. Couchbase への接続

Couchbase SDK といくつかの構成を追加することにより、Cluster を取得できます。spring.couchbase.* プロパティを使用して、接続をカスタマイズできます。通常、次の例に示すように、接続文字列 [GitHub] (英語) 、ユーザー名、パスワードを指定します。

Properties
spring.couchbase.connection-string=couchbase://192.168.1.123
spring.couchbase.username=user
spring.couchbase.password=secret
Yaml
spring:
  couchbase:
    connection-string: "couchbase://192.168.1.123"
    username: "user"
    password: "secret"

ClusterEnvironment 設定の一部をカスタマイズすることもできます。たとえば、次の構成は、新しい Bucket を開くためにタイムアウトを変更し、構成された SSL バンドルへの参照を使用して SSL サポートを有効にします。

Properties
spring.couchbase.env.timeouts.connect=3s
spring.couchbase.env.ssl.bundle=example
Yaml
spring:
  couchbase:
    env:
      timeouts:
        connect: "3s"
      ssl:
        bundle: "example"
詳細については、spring.couchbase.env.* プロパティを確認してください。より細かく制御するには、1 つ以上の ClusterEnvironmentBuilderCustomizer Bean を使用できます。

2.6.2. Spring Data Couchbase リポジトリ

Spring Data には、Couchbase のリポジトリサポートが含まれています。

リポジトリとドキュメントはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableCouchbaseRepositories と @EntityScan をそれぞれ使用して、リポジトリとドキュメントを検索する場所をカスタマイズできます。

Spring Data Couchbase の詳細については、リファレンスドキュメントを参照してください。

CouchbaseClientFactory Bean が利用可能であれば、他の Spring Bean と同じように自動構成された CouchbaseTemplate インスタンスを注入できます。これは、上記のように Cluster が使用可能で、バケット名が指定されている場合に発生します。

Properties
spring.data.couchbase.bucket-name=my-bucket
Yaml
spring:
  data:
    couchbase:
      bucket-name: "my-bucket"

次の例は、CouchbaseTemplate Bean を挿入する方法を示しています。

Java
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final CouchbaseTemplate template;

    public MyBean(CouchbaseTemplate template) {
        this.template = template;
    }

    // ...

    public String someMethod() {
        return this.template.getBucketName();
    }

}
Kotlin
import org.springframework.data.couchbase.core.CouchbaseTemplate
import org.springframework.stereotype.Component

@Component
class MyBean(private val template: CouchbaseTemplate) {

    // ...

    fun someMethod(): String {
        return template.bucketName
    }

}

自動構成によって提供される Bean をオーバーライドするために、独自の構成で定義できる Bean がいくつかあります。

  • couchbaseMappingContext という名前の CouchbaseMappingContext@Bean

  • couchbaseCustomConversions という名前の CustomConversions@Bean

  • couchbaseTemplate という名前の CouchbaseTemplate@Bean

独自の構成でこれらの名前をハードコードしないようにするには、Spring Data Couchbase が提供する BeanNames を再利用できます。たとえば、次のように、使用するコンバーターをカスタマイズできます。

Java
import org.assertj.core.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.couchbase.config.BeanNames;
import org.springframework.data.couchbase.core.convert.CouchbaseCustomConversions;

@Configuration(proxyBeanMethods = false)
public class MyCouchbaseConfiguration {

    @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
    public CouchbaseCustomConversions myCustomConversions() {
        return new CouchbaseCustomConversions(Arrays.asList(new MyConverter()));
    }

}
Kotlin
import org.assertj.core.util.Arrays
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.couchbase.config.BeanNames
import org.springframework.data.couchbase.core.convert.CouchbaseCustomConversions

@Configuration(proxyBeanMethods = false)
class MyCouchbaseConfiguration {

    @Bean(BeanNames.COUCHBASE_CUSTOM_CONVERSIONS)
    fun myCustomConversions(): CouchbaseCustomConversions {
        return CouchbaseCustomConversions(Arrays.asList(MyConverter()))
    }

}

2.7. LDAP

LDAP [Wikipedia] (ライトウェイトディレクトリアクセスプロトコル)は、IP ネットワークを介して分散ディレクトリ情報サービスにアクセスして維持するための、ベンダーに依存しないオープンな業界標準のアプリケーションプロトコルです。Spring Boot は、準拠する LDAP サーバーの自動構成と、UnboundID (英語) の組み込みインメモリ LDAP サーバーのサポートを提供します。

LDAP 抽象化は Spring Data LDAP [GitHub] (英語) によって提供されます。依存関係を便利な方法で収集するための spring-boot-starter-data-ldap 「スターター」があります。

2.7.1. LDAP サーバーへの接続

LDAP サーバーに接続するには、次の例に示すように、spring-boot-starter-data-ldap 「スターター」または spring-ldap-core への依存関係を宣言してから、application.properties でサーバーの URL を宣言してください。

Properties
spring.ldap.urls=ldap://myserver:1235
spring.ldap.username=admin
spring.ldap.password=secret
Yaml
spring:
  ldap:
    urls: "ldap://myserver:1235"
    username: "admin"
    password: "secret"

接続設定をカスタマイズする必要がある場合は、spring.ldap.base および spring.ldap.base-environment プロパティを使用できます。

LdapContextSource は、これらの設定に基づいて自動構成されます。DirContextAuthenticationStrategy Bean が使用可能な場合、自動構成された LdapContextSource に関連付けられます。たとえば PooledContextSource を使用するなど、カスタマイズする必要がある場合は、自動構成された LdapContextSource を注入できます。カスタマイズされた ContextSource に @Primary のフラグを立てて、自動構成された LdapTemplate がそれを使用するようにしてください。

2.7.2. Spring Data LDAP リポジトリ

Spring Data には、LDAP のリポジトリサポートが含まれています。

リポジトリとドキュメントはスキャンによって検出されます。デフォルトでは、自動構成パッケージがスキャンされます。@EnableLdapRepositories と @EntityScan をそれぞれ使用して、リポジトリとドキュメントを検索する場所をカスタマイズできます。

Spring Data LDAP の詳細については、リファレンスドキュメントを参照してください。

次の例に示すように、他の Spring Bean と同様に、自動構成された LdapTemplate インスタンスを注入することもできます。

Java
import java.util.List;

import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    private final LdapTemplate template;

    public MyBean(LdapTemplate template) {
        this.template = template;
    }

    // ...

    public List<User> someMethod() {
        return this.template.findAll(User.class);
    }

}
Kotlin
import org.springframework.ldap.core.LdapTemplate
import org.springframework.stereotype.Component

@Component
class MyBean(private val template: LdapTemplate) {

    // ...

    fun someMethod(): List<User> {
        return template.findAll(User::class.java)
    }

}

2.7.3. 組み込みインメモリ LDAP サーバー

テスト目的で、Spring Boot は UnboundID (英語) からのインメモリ LDAP サーバーの自動構成をサポートしています。サーバーを構成するには、次のように、com.unboundid:unboundid-ldapsdk に依存関係を追加し、spring.ldap.embedded.base-dn プロパティを宣言します。

Properties
spring.ldap.embedded.base-dn=dc=spring,dc=io
Yaml
spring:
  ldap:
    embedded:
      base-dn: "dc=spring,dc=io"

複数の base-dn 値を定義することは可能ですが、識別名には通常コンマが含まれるため、正しい表記を使用して定義する必要があります。

yaml ファイルでは、yaml リスト表記を使用できます。プロパティファイルでは、プロパティ名の一部としてインデックスを含める必要があります。

Properties
spring.ldap.embedded.base-dn[0]=dc=spring,dc=io
spring.ldap.embedded.base-dn[1]=dc=vmware,dc=com
Yaml
spring.ldap.embedded.base-dn:
  - "dc=spring,dc=io"
  - "dc=vmware,dc=com"

デフォルトでは、サーバーはランダムなポートで起動し、通常の LDAP サポートをトリガーします。spring.ldap.urls プロパティを指定する必要はありません。

クラスパスに schema.ldif ファイルがある場合、サーバーの初期化に使用されます。別のリソースから初期化スクリプトをロードする場合は、spring.ldap.embedded.ldif プロパティも使用できます。

デフォルトでは、LDIF ファイルを検証するために標準スキーマが使用されます。spring.ldap.embedded.validation.enabled プロパティを設定することにより、検証を完全にオフにできます。カスタム属性がある場合は、spring.ldap.embedded.validation.schema を使用してカスタム属性型またはオブジェクトクラスを定義できます。

2.8. InfluxDB

InfluxDB の自動構成は非推奨となり、独自の Spring Boot 統合を提供する新しい InfluxDB Java クライアント [GitHub] (英語) を優先して、Spring Boot 3.4 で削除される予定です。

InfluxDB (英語) は、運用監視、アプリケーションメトリクス、モノのインターネットセンサーデータ、リアルタイム分析などのフィールドにおける時系列データの高速で高可用性の保存と取得に最適化されたオープンソースの時系列データベースです。

2.8.1. InfluxDB への接続

influxdb-java クライアントがクラスパス上にあり、データベースの URL が spring.influx.url を使用して設定されている場合、Spring Boot は InfluxDB インスタンスを自動構成します。

InfluxDB への接続にユーザーとパスワードが必要な場合、それに応じて spring.influx.user および spring.influx.password プロパティを設定できます。

InfluxDB は OkHttp に依存しています。InfluxDB がバックグラウンドで使用する HTTP クライアントを調整する必要がある場合は、InfluxDbOkHttpClientBuilderProvider Bean を登録できます。

構成をさらに制御する必要がある場合は、InfluxDbCustomizer Bean の登録を検討してください。

3. 次のステップ

これで、さまざまなデータテクノロジで Spring Boot を使用する方法を理解できたはずです。ここから、さまざまなメッセージングテクノロジに対する Spring Boot のサポートと、アプリケーションで有効にする方法について読むことができます。