The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.
このページを編集

Quarkusでデータソースを設定

統一された設定モデルを使用して、Java Database Connectivity (JDBC) および Reactive ドライバーのデータソースを定義します。

アプリケーションは、データソースを使用してリレーショナルデータベースにアクセスします。 Quarkusは、Java Database Connectivity(JDBC)およびReactiveデータベースドライバー用のデータソースを定義するための統一された設定モデルを提供します。

Quarkus uses Agroal and Vert.x to provide high-performance, scalable datasource connection pooling for JDBC and reactive drivers. The quarkus-jdbc-* and quarkus-reactive-*-client extensions provide build-time optimizations and integrate configured datasources with Quarkus features such as security, health checks, and metrics.

リアクティブデータソースの消費と使用に関する詳細は、Quarkus Reactive SQLクライアントガイド を参照してください。

Additionally, refer to the Quarkus Hibernate ORM guide for information about consuming and using a JDBC datasource.

Quarkusでの datasources の設定入門

このセクションでは、基礎を理解しているユーザー向けに、データソースをすばやく設定するための概要とコードサンプルを示します。

より高度な設定とその例については、参照 を参照してください。

開発モードでのゼロコンフィグセットアップ

Quarkusでは、Dev Services機能によってデータベース設定が簡素化され、テストや開発(dev)モードでの実行のためのデータベース設定をゼロコンフィギュレーションで行うことができます。 開発モードでは、DevServicesを使用してQuarkusにデータベースを処理させる方法が推奨されます。一方、本番モードでは、Quarkusの外部で管理されるデータベースを指す明示的なデータベース設定の詳細を記述してください。

Dev Services を使用するには、 pom.xml ファイルに、希望するデータベースタイプに適したドライバーエクステンション (jdbc-postgresql など) を追加します。 開発モードでは、明示的なデータベース接続の詳細を記述しない場合、Quarkus が自動的にデータベースのセットアップを行い、アプリケーションとデータベース間の接続を行います。

When you provide user credentials, Quarkus configures the database to use them. This helps when you connect to the database with an external tool.

この機能を使用するには、データベースの種類に応じて、Docker または Podman コンテナーランタイムがインストールされていることを確認してください。 H2 などの特定のデータベースはインメモリモードで動作するため、コンテナーランタイムは必要ありません。

本番モードの実際の接続詳細の前に %prod. を付けて、それらが開発モードで適用されないようにします。 詳細は、「設定リファレンス」の プロファイル セクションを参照してください。

Dev Services の詳細については、 Dev Services の概要 を参照してください。

詳細およびオプション設定については、 Dev Services for databases を参照してください。

JDBC データソースの設定

  1. 選択したデータベースの正しい JDBC エクステンションを追加します。

    • quarkus-jdbc-db2

    • quarkus-jdbc-h2

    • quarkus-jdbc-mariadb

    • quarkus-jdbc-mssql

    • quarkus-jdbc-mysql

    • quarkus-jdbc-oracle

    • quarkus-jdbc-postgresql

  2. JDBC データソースを設定します:

    quarkus.datasource.db-kind=postgresql (1)
    quarkus.datasource.username=<your username>
    quarkus.datasource.password=<your password>
    
    quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test
    quarkus.datasource.jdbc.max-size=16
    1 この設定値は、クラスパスに複数のデータベースエクステンションがある場合にのみ必要です。

If only one viable extension is available, Quarkus assumes this is the correct one. When you add a driver to the test scope, Quarkus automatically includes it in testing.

JDBC接続プールのサイズ調整

To protect your database from overload during load peaks, size the pool appropriately to throttle the database load. The optimal pool size depends on many factors, such as the number of parallel application users or the nature of the workload.

プールサイズを小さく設定しすぎると、接続待ちの間にタイムアウトする リクエストが出てくるかもしれないことに注意してください。

プールサイズ調整プロパティーの詳細は、JDBC 設定リファレンス セクションを参照してください。

Reactiveデータソースの設定

  1. 選択したデータベースの正しいリアクティブエクステンションを追加します。

    • quarkus-reactive-db2-client

    • quarkus-reactive-mssql-client

    • quarkus-reactive-mysql-client

    • quarkus-reactive-oracle-client

    • quarkus-reactive-pg-client

  2. リアクティブデータソースを設定します:

    quarkus.datasource.db-kind=postgresql (1)
    quarkus.datasource.username=<your username>
    quarkus.datasource.password=<your password>
    
    quarkus.datasource.reactive.url=postgresql:///your_database
    quarkus.datasource.reactive.max-size=20
    1 この設定値は、クラスパスに複数の Reactive ドライバーエクステンションがある場合にのみ必要です。

データソースの設定

以下のセクションでは、単一または複数のデータソースの設定について説明します。 ここでは簡単のため、単一のデータソースをデフォルトの (無名の) データソースとして参照します。

単一のデータソースの設定

A datasource can be JDBC, reactive, or both. This depends on the configuration and the selection of project extensions.

  1. 以下の設定プロパティーでデータソースを定義します。 db-kind は、どのデータベースプラットフォームに接続するかを定義します。例えば、 h2 の場合:

    quarkus.datasource.db-kind=h2

    Quarkus derives the JDBC driver class from the db-kind database platform value.

    This step is required only if your application depends on multiple database drivers. If the application uses a single driver, Quarkus detects that driver automatically.

    Quarkusには現在、以下のデータベースのdb-kindが組み込まれています:

    • DB2: db2

    • H2: h2

    • MariaDB: mariadb

    • Microsoft SQL Server: mssql

    • MySQL: mysql

    • Oracle: oracle

    • PostgreSQL: postgresqlpgsql、または pg

    • ビルトインされていない種類のデータベースを使用するには、 other を使用し、JDBC ドライバーを明示的に定義します。

      Custom databases and drivers に記載されているように、Quarkus アプリケーションでは、JVM モードで任意の JDBC ドライバーを使用できます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときに、組み込みではないデータベースの種類を使用すると、機能しない可能性があります。

      ネイティブ実行可能ファイルをビルドする場合は、利用可能なJDBC Quarkusエクステンションを使用するか、特定のドライバー用にカスタムエクステンションを作成することをお勧めします。

  2. 以下のプロパティーを設定し、クレデンシャルを定義します:

    quarkus.datasource.username=<your username>
    quarkus.datasource.password=<your password>

    また、データソースに クレデンシャルプロバイダを使用することで、Vault からパスワードを取得することもできます。

Until now, the configuration has been the same regardless of whether you are using a JDBC or a reactive driver. After you define the database kind and credentials, the rest depends on the driver you are using. It is possible to use JDBC and a reactive driver simultaneously.

JDBC データソース

JDBC は最も一般的なデータベース接続パターンで、典型的には非リアクティブ型の Hibernate ORM と組み合わせて使用する場合に必要となります。

  1. To use a JDBC datasource, start by adding the necessary dependencies:

    1. 組み込みの JDBC ドライバーで使用する場合は、以下のリストからリレーショナルデータベースドライバー用の Quarkus エクステンションを選択して追加します。

      • H2 - quarkus-jdbc-h2

        You can configure H2 databases to run in "embedded mode"

        For suggestions regarding integration testing, see Testing with in-memory databases .

      • DB2 - quarkus-jdbc-db2

      • MariaDB - quarkus-jdbc-mariadb

      • Microsoft SQL Server - quarkus-jdbc-mssql

      • MySQL - quarkus-jdbc-mysql

      • Oracle - quarkus-jdbc-oracle

      • PostgreSQL - quarkus-jdbc-postgresql

      • その他のJDBCエクステンション (SQLite およびその ドキュメントなど) は、 Quarkiverse にあります。

        例えば、PostgreSQLドライバー依存関係を追加します:

        ./mvnw quarkus:add-extension -Dextensions="jdbc-postgresql"

        When you add a built-in JDBC driver extension, Quarkus also adds the quarkus-agroal extension. Agroal provides the JDBC connection pool for built-in and custom JDBC drivers. When you use a custom JDBC driver, add quarkus-agroal explicitly.

    2. カスタム JDBC ドライバーと共に使用する場合は、リレーショナルデータベースドライバーのエクステンションと一緒に、 quarkus-agroal 依存関係をプロジェクトに追加します:

      ./mvnw quarkus:add-extension -Dextensions="agroal"

      別のデータベースの JDBC ドライバーを使用するには、use a database with no built-in extension or with a different driver 組み込みのエクステンションがないデータベース、または異なるドライバーを使用するデータベースを利用してください。

  2. JDBC URL プロパティーを定義して、JDBC 接続を構成します:

    quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test

    Note the jdbc prefix in the property name. All JDBC-specific configuration properties have the jdbc prefix. For reactive datasources, the prefix is reactive.

JDBC の設定の詳細は、JDBC URL format reference および Quarkus extensions and database drivers reference を参照してください。

カスタムデータベースとドライバー

Quarkus がデータベース用の JDBC エクステンションを提供していない場合、または OpenTelemetry 用などの別の JDBC ドライバーを使用する必要がある場合は、JDBC ドライバーを明示的に設定できます。

エクステンションがない場合、JDBC ドライバーは JVM モードで正しく動作することが期待されます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときには機能しない可能性があります。 ネイティブ実行可能ファイルをビルドするには、既存の Quarkus JDBC エクステンションを使用するか、ドライバー用の新しいエクステンションを提供します。

JVMモードで、組込サポートのないデータベースへのアクセスを定義する例:
quarkus.datasource.db-kind=other
quarkus.datasource.jdbc.driver=oracle.jdbc.driver.OracleDriver
quarkus.datasource.jdbc.url=jdbc:oracle:thin:@192.168.1.12:1521/ORCL_SVC
quarkus.datasource.username=scott
quarkus.datasource.password=tiger

For details about JDBC configuration options and configuring other aspects, such as the connection pool size, refer to the JDBC configuration reference section.

データソースの消費

Hibernate ORMを使用する場合、Hibernateレイヤーは自動的にデータソースを選択し、それを使用します。

データソースへのコード内アクセスは、他のBeanと同様に以下のように取得します:

@Inject
AgroalDataSource defaultDataSource;

上記の例では、型は javax.sql.DataSource のサブタイプである AgroalDataSource です。 このため、 javax.sql.DataSource を注入される型として使用することもできます。

Oracle に関する考慮事項

issue #36265 で文書化されているように、Oracleでは接続を閉じるときにコミットされていないトランザクションが予期せずコミットされます。 つまり、Quarkusを停止すると、進行中のトランザクションが不完全であってもコミットされる可能性があります。

この動作は予期せぬものであり、データの損失につながる可能性があるため、インターセプターは接続を閉じる際に未完了のトランザクションをロールバックします。 しかし、XA トランザクションを使用している場合は、トランザクションマネージャがロールバックを行います。

If the behavior introduced in 3.18 causes issues for your workload, deactivate it by setting the -Dquarkus-oracle-no-automatic-rollback-on-connection-close system property to true. Make sure to report your use case in the issue tracker so we can adjust this behavior if needed, for example, with more permanent settings.

リアクティブデータソース

Quarkusには、リアクティブデータソースで使用できるリアクティブクライアントがいくつかあります。

  1. 対応するエクステンションをアプリケーションに追加します:

    • DB2: quarkus-reactive-db2-client

    • MariaDB/MySQL: quarkus-reactive-mysql-client

    • Microsoft SQL Server: quarkus-reactive-mssql-client

    • Oracle: quarkus-reactive-oracle-client

    • PostgreSQL: quarkus-reactive-pg-client

      インストールされているエクステンションは、データソースの設定で定義する quarkus.datasource.db-kind と一致している必要があります。

  2. ドライバーを追加したら、接続URLを設定し、接続プールの適切なサイズを定義します。

    quarkus.datasource.reactive.url=postgresql:///your_database
    quarkus.datasource.reactive.max-size=20
リアクティブ接続プールのサイズ調整

To protect your database from overload during load peaks, set the pool size to throttle database load. The correct pool size depends on factors such as the number of concurrent users and the workload type.

プールサイズを小さく設定しすぎると、接続待ちの間にタイムアウトする リクエストが出てくるかもしれないことに注意してください。

プールサイズ調整プロパティーの詳細は、Reactive データソース設定リファレンス セクションを参照してください。

JDBC とリアクティブデータソースの同時利用

When you add both a JDBC extension and a reactive datasource extension for the same db-kind, Quarkus creates both JDBC and reactive datasources by default.

  • JDBC および reactive データソースを同時に使用するには、以下を実行してください。

    %prod.quarkus.datasource.reactive.url=postgresql:///your_database
    %prod.quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test

JDBC データソースとリアクティブデータソースの両方を作成しない場合は、次の設定を使用します。

  • JDBC データソースを明示的に無効にするには、次のようにします:

    quarkus.datasource.jdbc=false
  • リアクティブデータソースを明示的に無効にするには、次のようにします:

    quarkus.datasource.reactive=false

    ほとんどの場合、JDBC ドライバーまたはリアクティブデータソースエクステンションのどちらかが存在し、両方は存在しないため、上記の構成はオプションになります。

複数のデータソースの設定

Hibernate ORM エクステンションは、設定プロパティーを使用した 永続化ユニット の定義をサポートしています。 各固有化ユニットに対して、任意のデータソースを指定します。

複数のデータソースの定義は、単一のデータソースを定義するのと同じように機能しますが、重要な変更点が 1 つあります。それは、各データソースの名前 (設定プロパティー) を指定する必要があることです。

以下の例では、3つの異なるデータソースを提供しています:

  • デフォルトのデータソース

  • users という名前のデータソース

  • inventory という名前のデータソース

それぞれの設定は次のとおりです。

quarkus.datasource.db-kind=h2
quarkus.datasource.username=username-default
quarkus.datasource.jdbc.url=jdbc:h2:mem:default
quarkus.datasource.jdbc.max-size=13

quarkus.datasource.users.db-kind=h2
quarkus.datasource.users.username=username1
quarkus.datasource.users.jdbc.url=jdbc:h2:mem:users
quarkus.datasource.users.jdbc.max-size=11

quarkus.datasource.inventory.db-kind=h2
quarkus.datasource.inventory.username=username2
quarkus.datasource.inventory.jdbc.url=jdbc:h2:mem:inventory
quarkus.datasource.inventory.jdbc.max-size=12

設定プロパティーに余分なセクションがあることに注意してください。 構文は次の通りです: quarkus.datasource.[optional name.][datasource property] .

Even when you install only one database extension, named datasources must set at least one build-time property so Quarkus can detect them. In most cases, set db-kind.

You can also set Dev Services properties to create named datasources as described in the Dev Services for Databases guide.

名前付きデータソース注入

When you configure multiple datasources, each DataSource also has the io.quarkus.agroal.DataSource qualifier with the datasource name as the value.

After you configure three datasources as described in the previous section, inject each datasource as follows:

@Inject
AgroalDataSource defaultDataSource;

@Inject
@DataSource("users")
AgroalDataSource usersDataSource;

@Inject
@DataSource("inventory")
AgroalDataSource inventoryDataSource;

データソースをアクティブ化または非アクティブ化する

データソースがビルド時に設定され、そのURLが実行時に設定されると、デフォルトでアクティブになります。 Quarkusでは、アプリケーションの起動時に、対応するJDBC接続プールまたはリアクティブクライアントが起動します。

ランタイムにデータソースを非アクティブ化するには、次のいずれかを実行します。

  • quarkus.datasource[.optional name].jdbc.url または quarkus.datasource[.optional name].reactive.url を設定しないでください。

  • quarkus.datasource[.optional name].activefalse に設定します。

データソースがアクティブでない場合は、以下のようになります。

  • アプリケーションの起動時に、データソースがデータベースに接続しようとしません。

  • データソースは ヘルスチェック を行いません。

  • @Inject DataSource ds@Inject Pool pool など、データソースを含む静的 CDI インジェクション・ポイントは、アプリケーションの起動を失敗させます。

  • Dynamic retrieval of the datasource, such as through CDI.getBeanContainer(), Arc.instance(), or an injected Instance<DataSource>, causes an exception to be thrown.

  • データソースを消費する他のQuarkusエクステンションによって、アプリケーションの起動が失敗する可能性があります。

    In this case, you must also deactivate those other extensions. To see an example of this scenario, refer to the Activate/deactivate persistence units section of the Hibernate ORM guide. For Hibernate ORM, Quarkus deactivates the persistence unit when the datasource is inactive.

この機能は、アプリケーションが実行時に定義済みのセットから1つのデータソースを選択しなければならない場合に特に便利です。

複数のデータソースを実行時に選択できるように設定する例:
quarkus.datasource."pg".db-kind=postgres
quarkus.datasource."pg".active=false
quarkus.datasource."pg".jdbc.url=jdbc:postgresql:///your_database

quarkus.datasource."oracle".db-kind=oracle
quarkus.datasource."oracle".active=false
quarkus.datasource."oracle".jdbc.url=jdbc:oracle:thin:@localhost:1521/your_database

実行時quarkus.datasource."pg".active=true を設定すると、PostgreSQL データソースのみが使用可能になります。 実行時に quarkus.datasource."oracle".active=true を設定すると、Oracle データソースのみが使用可能になります。

カスタム設定プロファイル を使用すると、この設定が簡単になります。以下のプロファイル固有の構成を上記の構成に追加することで、 quarkus.profile 設定して 、実行時に永続化ユニットまたはデータソースを選択できます。例えば、 quarkus.profile=prod,pg または quarkus.profile=prod,oracle を使用します。

%pg.quarkus.hibernate-orm."pg".active=true
%pg.quarkus.datasource."pg".active=true
# Add any PostgreSQL-related runtime configuration here, prefixed with "%pg."

%oracle.quarkus.hibernate-orm."oracle".active=true
%oracle.quarkus.datasource."oracle".active=true
# Add any Oracle-related runtime configuration here, prefixed with "%oracle."

この設定では、アクティブな データソースのみにアクセスできるようにします。 これを実現するには、 @Any アノテーションを使用して InjectableInstance<DataSource> または InjectableInstance<Pool> を挿入し、getActive() を呼び出します。

import io.quarkus.arc.InjectableInstance;
@ApplicationScoped
public class MyConsumer {
    @Inject
    @Any
    InjectableInstance<DataSource> dataSource;

    public void doSomething() {
        DataSource activeDataSource = dataSource.getActive();
        // ...
    }
}

Alternatively, define a CDI bean producer for the default datasource. The bean producer redirects to the active named datasource. The application can then inject the default datasource directly, as shown below:

public class MyProducer {
    @Inject
    @DataSource("pg")
    InjectableInstance<DataSource> pgDataSourceBean; (1)

    @Inject
    @DataSource("oracle")
    InjectableInstance<DataSource> oracleDataSourceBean;

    @Produces (2)
    @ApplicationScoped
    public DataSource dataSource() {
        if (pgDataSourceBean.getHandle().getBean().isActive()) { (3)
            return pgDataSourceBean.get();
        } else if (oracleDataSourceBean.getHandle().getBean().isActive()) { (3)
            return oracleDataSourceBean.get();
        } else {
            throw new RuntimeException("No active datasource!");
        }
    }
}

@ApplicationScoped
public class MyConsumer {
    @Inject
    DataSource dataSource; (4)

    public void doSomething() {
        // .. just use the injected datasource ...
    }
}
1 DataSourceAgroalDatasource を直接注入しないでください。非アクティブなBeanを注入すると、起動に失敗します。 代わりに InjectableInstance<DataSource> または InjectableInstance<AgroalDataSource> を注入します。
2 デフォルトのデータソースを定義するCDIプロデューサー・メソッドを宣言します。これは、PostgreSQL または Oracle のいずれかを選択します。
3 ビーンを取得する前に、ビーンがアクティブかどうかをチェックします。
4 唯一のアクティブなデータソースをインジェクトします。

単一のトランザクションで複数のデータソースを使用する

デフォルトでは、データソースでの XA サポートは無効になっています。 したがって、トランザクションには 1 つのデータソースしか含めることができません。 同じトランザクションで複数の非 XA データソースにアクセスしようとすると、次のような例外が発生します。

...
Caused by: java.sql.SQLException: Exception in association of connection to existing transaction
        at io.agroal.narayana.NarayanaTransactionIntegration.associate(NarayanaTransactionIntegration.java:130)
        ...
Caused by: java.sql.SQLException: Failed to enlist. Check if a connection from another datasource is already enlisted to the same transaction
        at io.agroal.narayana.NarayanaTransactionIntegration.associate(NarayanaTransactionIntegration.java:121)
        ...

同じトランザクションで複数の JDBC データソースを使用できるようにするには、次の手順を実行します。

  1. JDBC ドライバーが XA をサポートしていることを確認してください。 すべての supported JDBC drivers do サポート対象の JDBC ドライバーはサポートしていますが、other JDBC drivers 他の JDBC ドライバーはサポートしていない場合があります。

  2. データベースサーバーが XA を有効化するように設定されていることを確認します。

  3. Enable XA support explicitly for each relevant datasource by setting quarkus.datasource[.optional name].jdbc.transactions to xa.

XA を使用すると、1 つのデータソースでのロールバックにより、トランザクションに登録されている他のすべてのデータソースでのロールバックがトリガーされます。

現時点では、リアクティブデータソース上の XA トランザクションはサポートされていません。

トランザクションにデータソース以外のリソースが含まれる場合は、そのリソースで XA トランザクションがサポートされていない可能性や、追加の設定が必要になる可能性があることに注意してください。

1 つのデータソースに対して XA を有効にできない場合:

  • 1 つだけを除く すべてのデータソースに対して XA を有効にすることは、Last Resource Commit Optimization (LRCO) を通じて引き続きサポートされている点に注意してください。

  • 1 つのデータソースのロールバックによって他のデータソースのロールバックをトリガーする必要がない場合は、コードを複数のトランザクションに分割することを検討してください。 これを行うには、QuarkusTransaction.requiringNew()/@Transactional(REQUIRES_NEW) (推奨) または UserTransaction (より複雑なユースケースの場合) を使用します。

他の解決策がなく、Quarkus 3.8以前との互換性が必要な場合は、 quarkus.transaction-manager.unsafe-multiple-last-resourcesallow に設定して、複数の非XAデータソースにわたる安全でないトランザクション処理を有効にします。

このプロパティを allow に設定すると、トランザクションのロールバックが最後の非XAデータソースにのみ適用され、他の非XAデータソースはすでに変更をコミットしている可能性があります。この場合、システムは一貫性のない状態になる可能性があります。

あるいは、同じように安全でない動作を許可しますが、その際には警告を表示します:

  • プロパティを warn-each に設定すると、問題のあるトランザクション ごとに 警告がログに記録されます。

  • このプロパティを warn-first に設定すると、 最初の 違反トランザクションに対して警告がログに記録されます。

この設定プロパティの使用は推奨しておらず、将来的に削除する予定です。アプリケーションを適宜更新してください。このオプションを維持することが正当な使用例であると考えられる場合は、 Quarkusのトラッカー にその理由を説明するissueを作成してください。

データソースの統合

データソースのヘルスチェック

quarkus-smallrye-health エクステンションを使用する場合、 quarkus-agroal およびリアクティブクライアントエクステンションは、 データソースを検証するためのreadiness ヘルスチェックを自動的に追加します。

アプリケーションのヘルスチェックエンドポイント /q/health/ready (デフォルト) にアクセスすると、データソースの検証状況に関する情報を受け取ります。 複数のデータソースがある場合は、すべてのデータソースがチェックされ、データソースの検証に失敗した場合は、ステータスが DOWN に変わります。

You can disable this behavior by setting quarkus.datasource.health.enabled=false.

特定のデータソースのみをヘルスチェックから除外するには、以下を使用します。

quarkus.datasource."datasource-name".health-exclude=true

データソースのメトリクス

When you add the quarkus-micrometer extension, quarkus-agroal can publish datasource metrics to the metrics registry. To enable these metrics, set quarkus.datasource.metrics.enabled=true.

For the published metrics to report values, Agroal must enable its internal metrics collection. By default, Agroal enables internal metrics collection for all datasources when a metrics extension is present and quarkus.datasource.metrics.enabled is set to true.

To disable metrics for a specific datasource, set quarkus.datasource.jdbc.metrics.enabled=false. For a named datasource, set quarkus.datasource.<datasource name>.jdbc.metrics.enabled=false. This setting stops internal metrics collection and stops exposing datasource metrics at the /q/metrics endpoint.

To enable internal metrics collection explicitly for the default data source, set quarkus.datasource.jdbc.metrics.enabled=true. To enable internal metrics collection explicitly for a named data source, set quarkus.datasource.<datasource name>.jdbc.metrics.enabled=true. This enables internal metrics collection even when you do not add a metrics extension. You can access the collected metrics programmatically by calling dataSource.getMetrics() on an injected AgroalDataSource instance.

When metrics collection is disabled for a data source, all metric values are zero.

データソースのトレース

データソースでトレースを使用するには、プロジェクトに quarkus-opentelemetry エクステンションを追加する必要があります。

トレーシングを有効化するために別のドライバーを宣言する必要はありません。 JDBC ドライバーを使用する場合は、OpenTelemetry エクステンションの手順 に従う必要があります。

すべてのトレースインフラストラクチャーが整っていても、データソーストレースはデフォルトでは有効になっていません。そのため、次のプロパティーを設定して有効にする必要があります。

# enable tracing
quarkus.datasource.jdbc.telemetry=true

Narayanaトランザクションマネージャの統合

Narayana JTAエクステンションも利用可能であれば、統合は自動的に行われます。

transactions 設定プロパティーを設定することで、これをオーバーライドできます。

  • quarkus.datasource.jdbc.transactions (デフォルトの無名データソースの場合)

  • quarkus.datasource.<datasource-name>.jdbc.transactions (名前付きデータソースの場合)

When a datasource is configured for XA transactions by setting quarkus.datasource[.optional name].jdbc.transactions=xa and the transaction recovery system is enabled by using quarkus.transaction-manager.enable-recovery=true, the datasource is automatically registered for recovery. This is the preferred and safe default. You can override this behavior for individual datasources by setting quarkus.datasource.jdbc.enable-recovery=false or quarkus.datasource."datasource-name".jdbc.enable-recovery=false.

Change this setting only in advanced use cases and only if you are certain recovery is not required. Incorrect configuration can lead to data loss, data unavailability, or both, due to resources remaining locked indefinitely.

For more information, see the Configuration reference section below. To facilitate the storage of transaction logs in a database by using JDBC, see the Configuring transaction logs to be stored in a datasource section of the Using transactions in Quarkus guide.

インメモリーデータベースを使用したテスト

The recommended approach for testing against databases is to use the same database as production to get test results that match production behavior as closely as possible. Dev Services simplifies this approach by requiring no configuration and starting quickly.

For scenarios where neither Dev Services nor a custom database setup is possible, you can use a JVM based database such as H2 in embedded mode.

サポートと制限

Embedded databases such as H2 work in JVM mode.

In native mode, embedding H2 in the native image is not recommended. Use a remote connection to a separate database, or use Dev Services to run the database outside the native image.

統合テストの実行

  1. 次の Maven コーディネートの下にある追加ツールを提供するアーティファクトに依存関係を追加します。

    • io.quarkus:quarkus-test-h2 H2の場合

      You can test your application even when it is compiled into a native executable, while the database will run as a JVM process.

  2. Add the following annotation to any class in your integration tests to run the tests on both the JVM and native executables:

    • @QuarkusTestResource(H2DatabaseTestResource.class)

      これにより、テストスイートは、テスト実行に必要な別プロセスで管理データベースを起動し、終了します。

      H2の例
      package my.app.integrationtests.db;
      
      import io.quarkus.test.common.QuarkusTestResource;
      import io.quarkus.test.h2.H2DatabaseTestResource;
      
      @QuarkusTestResource(H2DatabaseTestResource.class)
      public class TestResources {
      }
  3. マネージドデータベースへの接続を設定します:

    quarkus.datasource.db-kind=h2
    quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:test

参照

共通データソース設定リファレンス

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Whether or not a health check is published in case the smallrye-health extension is present.

This is a global setting and is not specific to a datasource.

Environment variable: QUARKUS_DATASOURCE_HEALTH_ENABLED

Show more

boolean

true

Whether datasource metrics are published in case a metrics extension is present.

This is a global setting and is not specific to a datasource.

This is different from the quarkus.datasource."datasource name".jdbc.metrics.enabled property that needs to be set on the JDBC datasource level to enable collection of metrics for that datasource.

Environment variable: QUARKUS_DATASOURCE_METRICS_ENABLED

Show more

boolean

false

quarkus.datasource."datasource-name".db-kind

The kind of database we will connect to (e.g. h2, postgresql…​).

Environment variable: QUARKUS_DATASOURCE_DB_KIND

Show more

string

quarkus.datasource."datasource-name".db-version

The version of the database we will connect to (e.g. '10.0').

The version number set here should follow the same numbering scheme as the string returned by java.sql.DatabaseMetaData#getDatabaseProductVersion() for your database’s JDBC driver. This numbering scheme may be different from the most popular one for your database; for example Microsoft SQL Server 2016 would be version 13.

As a rule, the version set here should be as high as possible, but must be lower than or equal to the version of any database your application will connect to.

A high version will allow better performance and using more features (e.g. Hibernate ORM may generate more efficient SQL, avoid workarounds and take advantage of more database features), but if it is higher than the version of the database you want to connect to, it may lead to runtime exceptions (e.g. Hibernate ORM may generate invalid SQL that your database will reject).

Some extensions (like the Hibernate ORM extension) will try to check this version against the actual database version on startup, leading to a startup failure when the actual version is lower or simply a warning in case the database cannot be reached.

The default for this property is specific to each extension; the Hibernate ORM extension will default to the oldest version it supports.

Environment variable: QUARKUS_DATASOURCE_DB_VERSION

Show more

string

quarkus.datasource."datasource-name".health-exclude

Whether this particular data source should be excluded from the health check if the general health check for data sources is enabled.

By default, the health check includes all configured data sources (if it is enabled).

Environment variable: QUARKUS_DATASOURCE_HEALTH_EXCLUDE

Show more

boolean

false

quarkus.datasource."datasource-name".active

Whether this datasource should be active at runtime.

Environment variable: QUARKUS_DATASOURCE_ACTIVE

Show more

boolean

`true` if the URL is set, `false` otherwise

quarkus.datasource."datasource-name".username

The datasource username

Environment variable: QUARKUS_DATASOURCE_USERNAME

Show more

string

quarkus.datasource."datasource-name".password

The datasource password

Environment variable: QUARKUS_DATASOURCE_PASSWORD

Show more

string

quarkus.datasource."datasource-name".credentials-provider

The credentials provider name

Environment variable: QUARKUS_DATASOURCE_CREDENTIALS_PROVIDER

Show more

string

quarkus.datasource."datasource-name".credentials-provider-name

The credentials provider bean name.

This is a bean name (as in @Named) of a bean that implements CredentialsProvider. It is used to select the credentials provider bean when multiple exist. This is unnecessary when there is only one credentials provider available.

For Vault, the credentials provider bean name is vault-credentials-provider.

Environment variable: QUARKUS_DATASOURCE_CREDENTIALS_PROVIDER_NAME

Show more

string

Dev Services

デフォルト

quarkus.datasource."datasource-name".devservices.enabled

Whether this Dev Service should start with the application in dev mode or tests.

Dev Services are enabled by default unless connection configuration (e.g. the JDBC URL or reactive client URL) is set explicitly.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_ENABLED

Show more

boolean

quarkus.datasource."datasource-name".devservices.image-name

The container image name for container-based Dev Service providers.

This has no effect if the provider is not a container-based database, such as H2 or Derby.

Defaults depend on the configured datasource:

  • DB2: icr.io/db2_community/db2:12.1.0.0

  • MariaDB: docker.io/library/mariadb:12.1

  • Microsoft SQL Server: mcr.microsoft.com/mssql/server:2022-latest

  • MySQL: docker.io/library/mysql:9.5

  • Oracle Express Edition: docker.io/gvenzl/oracle-free:23-slim-faststart

  • PostgreSQL: docker.io/library/postgres:18

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_IMAGE_NAME

Show more

string

quarkus.datasource."datasource-name".devservices.container-env."environment-variable-name"

Environment variables that are passed to the container.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_CONTAINER_ENV__ENVIRONMENT_VARIABLE_NAME_

Show more

Map<String,String>

quarkus.datasource."datasource-name".devservices.container-properties."property-key"

Generic properties that are passed for additional container configuration.

Properties defined here are database-specific and are interpreted specifically in each database dev service implementation.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_CONTAINER_PROPERTIES__PROPERTY_KEY_

Show more

Map<String,String>

quarkus.datasource."datasource-name".devservices.properties."property-key"

Generic properties that are added to the database connection URL.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_PROPERTIES__PROPERTY_KEY_

Show more

Map<String,String>

quarkus.datasource."datasource-name".devservices.port

Optional fixed port the dev service will listen to.

If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_PORT

Show more

int

quarkus.datasource."datasource-name".devservices.command

The container start command to use for container-based Dev Service providers.

This has no effect if the provider is not a container-based database, such as H2 or Derby.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_COMMAND

Show more

string

quarkus.datasource."datasource-name".devservices.db-name

The database name to use if this Dev Service supports overriding it.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_DB_NAME

Show more

string

quarkus.datasource."datasource-name".devservices.username

The username to use if this Dev Service supports overriding it.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_USERNAME

Show more

string

quarkus.datasource."datasource-name".devservices.password

The password to use if this Dev Service supports overriding it.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_PASSWORD

Show more

string

quarkus.datasource."datasource-name".devservices.init-script-path

The paths to SQL scripts to be loaded from the classpath and applied to the Dev Service database.

This has no effect if the provider is not a container-based database, such as H2 or Derby.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_INIT_SCRIPT_PATH

Show more

list of string

quarkus.datasource."datasource-name".devservices.init-privileged-script-path

The paths to SQL scripts to be loaded from the classpath and applied to the Dev Service database using the SYS privileged user. Not all databases provide a privileged user. In these cases, the property is ignored. This has no effect if the provider is not a container-based database, such as H2 or Derby.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_INIT_PRIVILEGED_SCRIPT_PATH

Show more

list of string

quarkus.datasource."datasource-name".devservices.volumes."host-path"

The volumes to be mapped to the container.

The map key corresponds to the host location; the map value is the container location. If the host location starts with "classpath:", the mapping loads the resource from the classpath with read-only permission.

When using a file system location, the volume will be generated with read-write permission, potentially leading to data loss or modification in your file system.

This has no effect if the provider is not a container-based database, such as H2 or Derby.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_VOLUMES__HOST_PATH_

Show more

Map<String,String>

quarkus.datasource."datasource-name".devservices.reuse

Whether to keep Dev Service containers running after a dev mode session or test suite execution to reuse them in the next dev mode session or test suite execution.

Within a dev mode session or test suite execution, Quarkus will always reuse Dev Services as long as their configuration (username, password, environment, port bindings, …​) did not change. This feature is specifically about keeping containers running when Quarkus is not running to reuse them across runs.

This feature needs to be enabled explicitly in testcontainers.properties, may require changes to how you configure data initialization in dev mode and tests, and may leave containers running indefinitely, forcing you to stop and remove them manually. See this section of the documentation for more information.

This configuration property is set to true by default, so it is mostly useful to disable reuse, if you enabled it in testcontainers.properties but only want to use it for some of your Quarkus applications or datasources.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_REUSE

Show more

boolean

true

quarkus.datasource."datasource-name".devservices.show-logs

Whether the logs should be consumed by the JBoss logger.

This has no effect if the provider is not a container-based database, such as H2 or Derby.

Environment variable: QUARKUS_DATASOURCE_DEVSERVICES_SHOW_LOGS

Show more

boolean

false

JDBC 設定リファレンス

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Activate or disable the dev ui page.

Environment variable: QUARKUS_DATASOURCE_DEV_UI_ENABLED

Show more

boolean

true

Allow sql queries in the Dev UI page

Environment variable: QUARKUS_DATASOURCE_DEV_UI_ALLOW_SQL

Show more

boolean

false

Append this to the select done to fetch the table values. eg: LIMIT 100 or TOP 100

Environment variable: QUARKUS_DATASOURCE_DEV_UI_APPEND_TO_DEFAULT_SELECT

Show more

string

Allowed database host. By default, only localhost is allowed. Any provided host here will also be allowed. You can use the special value * to allow any DB host.

Environment variable: QUARKUS_DATASOURCE_DEV_UI_ALLOWED_DB_HOST

Show more

string

quarkus.datasource."datasource-name".jdbc

If we create a JDBC datasource for this datasource.

Environment variable: QUARKUS_DATASOURCE_JDBC

Show more

boolean

true

quarkus.datasource."datasource-name".jdbc.driver

The datasource driver class name

Environment variable: QUARKUS_DATASOURCE_JDBC_DRIVER

Show more

string

quarkus.datasource."datasource-name".jdbc.transactions

Whether we want to use regular JDBC transactions, XA, or disable all transactional capabilities.

When enabling XA you will need a driver implementing javax.sql.XADataSource.

Environment variable: QUARKUS_DATASOURCE_JDBC_TRANSACTIONS

Show more

enabledIntegrate the JDBC Datasource with the JTA TransactionManager of Quarkus. This is the default., xaSimilarly to enabled, also enables integration with the JTA TransactionManager of Quarkus, but enabling XA transactions as well. Requires a JDBC driver implementing javax.sql.XADataSource, disabledDisables the Agroal integration with the Narayana TransactionManager. This is typically a bad idea, and is only useful in special cases\: make sure to not use this without having a deep understanding of the implications.

enabledIntegrate the JDBC Datasource with the JTA TransactionManager of Quarkus. This is the default.

quarkus.datasource."datasource-name".jdbc.telemetry

Enable OpenTelemetry JDBC instrumentation.

Environment variable: QUARKUS_DATASOURCE_JDBC_TELEMETRY

Show more

boolean

false

quarkus.datasource."datasource-name".jdbc.metrics.enabled

Enable metrics collection for this datasource.

Environment variable: QUARKUS_DATASOURCE_JDBC_METRICS_ENABLED

Show more

boolean

quarkus.datasource."datasource-name".jdbc.url

The datasource URL

Environment variable: QUARKUS_DATASOURCE_JDBC_URL

Show more

string

quarkus.datasource."datasource-name".jdbc.initial-size

The initial size of the pool. Usually you will want to set the initial size to match at least the minimal size, but this is not enforced so to allow for architectures which prefer a lazy initialization of the connections on boot, while being able to sustain a minimal pool size after boot.

Environment variable: QUARKUS_DATASOURCE_JDBC_INITIAL_SIZE

Show more

int

quarkus.datasource."datasource-name".jdbc.min-size

The datasource pool minimum size

Environment variable: QUARKUS_DATASOURCE_JDBC_MIN_SIZE

Show more

int

0

quarkus.datasource."datasource-name".jdbc.max-size

The datasource pool maximum size

Environment variable: QUARKUS_DATASOURCE_JDBC_MAX_SIZE

Show more

int

50

quarkus.datasource."datasource-name".jdbc.background-validation-interval

The interval at which we validate idle connections in the background.

Set to 0 to disable background validation.

Environment variable: QUARKUS_DATASOURCE_JDBC_BACKGROUND_VALIDATION_INTERVAL

Show more

Duration 

2M

quarkus.datasource."datasource-name".jdbc.foreground-validation-interval

Perform foreground validation on connections that have been idle for longer than the specified interval.

Environment variable: QUARKUS_DATASOURCE_JDBC_FOREGROUND_VALIDATION_INTERVAL

Show more

Duration 

quarkus.datasource."datasource-name".jdbc.login-timeout

Maximum time to wait while attempting to connect to a database. The actual implementation of login timeout could be different in various drivers. (e.g. driver could only cover the authentication and not the entire connection creation phase)

Environment variable: QUARKUS_DATASOURCE_JDBC_LOGIN_TIMEOUT

Show more

Duration 

By default, there is no login timeout set.

quarkus.datasource."datasource-name".jdbc.acquisition-timeout

The timeout before cancelling the acquisition of a new connection

Environment variable: QUARKUS_DATASOURCE_JDBC_ACQUISITION_TIMEOUT

Show more

Duration 

5S

quarkus.datasource."datasource-name".jdbc.leak-detection-interval

The interval at which we check for connection leaks.

Environment variable: QUARKUS_DATASOURCE_JDBC_LEAK_DETECTION_INTERVAL

Show more

Duration 

This feature is disabled by default.

quarkus.datasource."datasource-name".jdbc.idle-removal-interval

The interval at which we try to remove idle connections.

Environment variable: QUARKUS_DATASOURCE_JDBC_IDLE_REMOVAL_INTERVAL

Show more

Duration 

5M

quarkus.datasource."datasource-name".jdbc.max-lifetime

The max lifetime of a connection.

Environment variable: QUARKUS_DATASOURCE_JDBC_MAX_LIFETIME

Show more

Duration 

By default, there is no restriction on the lifespan of a connection.

quarkus.datasource."datasource-name".jdbc.transaction-isolation-level

The transaction isolation level.

Environment variable: QUARKUS_DATASOURCE_JDBC_TRANSACTION_ISOLATION_LEVEL

Show more

undefined, none, read-uncommitted, read-committed, repeatable-read, serializable

quarkus.datasource."datasource-name".jdbc.extended-leak-report

Collect and display extra troubleshooting info on leaked connections.

Environment variable: QUARKUS_DATASOURCE_JDBC_EXTENDED_LEAK_REPORT

Show more

boolean

false

quarkus.datasource."datasource-name".jdbc.flush-on-close

Allows connections to be flushed upon return to the pool. It’s not enabled by default.

Environment variable: QUARKUS_DATASOURCE_JDBC_FLUSH_ON_CLOSE

Show more

boolean

false

quarkus.datasource."datasource-name".jdbc.detect-statement-leaks

When enabled, Agroal will be able to produce a warning when a connection is returned to the pool without the application having closed all open statements. This is unrelated with tracking of open connections. Disable for peak performance, but only when there’s high confidence that no leaks are happening.

Environment variable: QUARKUS_DATASOURCE_JDBC_DETECT_STATEMENT_LEAKS

Show more

boolean

true

quarkus.datasource."datasource-name".jdbc.new-connection-sql

Query executed when first using a connection.

Environment variable: QUARKUS_DATASOURCE_JDBC_NEW_CONNECTION_SQL

Show more

string

quarkus.datasource."datasource-name".jdbc.validation-query-sql

Query executed to validate a connection.

Environment variable: QUARKUS_DATASOURCE_JDBC_VALIDATION_QUERY_SQL

Show more

string

quarkus.datasource."datasource-name".jdbc.validation-query-timeout

The timeout for the connection validation query

Environment variable: QUARKUS_DATASOURCE_JDBC_VALIDATION_QUERY_TIMEOUT

Show more

Duration 

quarkus.datasource."datasource-name".jdbc.validate-on-borrow

Forces connection validation prior to acquisition (foreground validation) regardless of the idle status.

Because of the overhead of performing validation on every call, it’s recommended to rely on default idle validation instead, and to leave this to false.

Environment variable: QUARKUS_DATASOURCE_JDBC_VALIDATE_ON_BORROW

Show more

boolean

false

quarkus.datasource."datasource-name".jdbc.pooling-enabled

Disable pooling to prevent reuse of Connections. Use this when an external pool manages the life-cycle of Connections.

Environment variable: QUARKUS_DATASOURCE_JDBC_POOLING_ENABLED

Show more

boolean

true

quarkus.datasource."datasource-name".jdbc.enable-recovery

Whether to enable recovery for this datasource.

Normally a transaction manager will call xa_recover () on an XA connection during recovery to obtain a list of transaction branches that are currently in a prepared or heuristically completed state. However, it can happen that multiple XA connections connect to the same datasource which would all return the same set of branches and for reasons of improved performance only one should be used for recover() calls. The default value for this configuration property is true because when there is only one connection it is vital for data consistency that the connection is able to report its list of prepared or heuristically completed branches.

Environment variable: QUARKUS_DATASOURCE_JDBC_ENABLE_RECOVERY

Show more

boolean

true

quarkus.datasource."datasource-name".jdbc.transaction-requirement

Require an active transaction when acquiring a connection. Recommended for production. WARNING: Some extensions acquire connections without holding a transaction for things like schema updates and schema validation. Setting this setting to STRICT may lead to failures in those cases.

Environment variable: QUARKUS_DATASOURCE_JDBC_TRANSACTION_REQUIREMENT

Show more

off, warn, strict

quarkus.datasource."datasource-name".jdbc.additional-jdbc-properties."property-key"

Other unspecified properties to be passed to the JDBC driver when creating new connections.

Environment variable: QUARKUS_DATASOURCE_JDBC_ADDITIONAL_JDBC_PROPERTIES__PROPERTY_KEY_

Show more

Map<String,String>

quarkus.datasource."datasource-name".jdbc.telemetry.enabled

Enable OpenTelemetry JDBC instrumentation.

Environment variable: QUARKUS_DATASOURCE_JDBC_TELEMETRY_ENABLED

Show more

boolean

false if quarkus.datasource.jdbc.telemetry=false and true if quarkus.datasource.jdbc.telemetry=true

quarkus.datasource."datasource-name".jdbc.enable-metrics

This property is deprecated.

Enable datasource metrics collection. If unspecified, collecting metrics will be enabled by default if a metrics extension is active.

Please use quarkus-micrometer and the quarkus.datasource.metrics.enabled property

Environment variable: QUARKUS_DATASOURCE_JDBC_ENABLE_METRICS

Show more

boolean

期間フォーマットについて

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

JDBC URL リファレンス

Each supported database has its own JDBC URL configuration options. The following sections describe each JDBC URL and provide a link to the official documentation.

DB2

jdbc:db2://<serverName>[:<portNumber>]/<databaseName>[:<key1>=<value>;[<key2>=<value2>;]]

jdbc:db2://localhost:50000/MYDB:user=dbadm;password=dbadm;

URL構文と追加のサポートされるオプションの詳細については、 公式ドキュメント を参照してください。

H2

jdbc:h2:{ {.|mem:}[name] | [file:]fileName | {tcp|ssl}:[//]server[:port][,server2[:port]]/name }[;key=value…​]

jdbc:h2:tcp://localhost/~/test, jdbc:h2:mem:myDB

H2は、組み込みモードでもサーバーモードでも動作するデータベースです。 ファイルストレージを使用することも、完全にメモリ内で実行することもできます。 これらのオプションはすべて、上記のように利用可能です。

詳しくは 公式ドキュメント をご覧ください。

MariaDB

jdbc:mariadb:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…​]/[database][?<key1>=<value1>[&<key2>=<value2>]] hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]

jdbc:mariadb://localhost:3306/test

詳しくは 公式ドキュメント をご覧ください。

Microsoft SQL server

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]

jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks

詳しくは 公式ドキュメント をご覧ください。

MySQL

jdbc:mysql:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…​]/[database][?<key1>=<value1>[&<key2>=<value2>]] hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]

jdbc:mysql://localhost:3306/test

詳しくは 公式ドキュメント をご覧ください。

MySQL の制限

When you compile an application into a native image, the following limitations apply to MySQL Connector/J integrations:

  • Quarkus disables Java Management Extensions (JMX) support because it does not work in native mode.

  • Quarkus disables Oracle Cloud Infrastructure (OCI) integration because it does not work in native mode.

  • Quarkus disables the MySQL Connector/J OpenTelemetry integration and relies on the Agroal integration instead.

    If you need the MySQL Connector/J OpenTelemetry integration, enable it explicitly by setting quarkus.datasource.jdbc.additional-jdbc-properties.openTelemetry=PREFERRED. For more information, see MySQL Connector/J documentation.

    When you enable this option and also add the quarkus-opentelemetry extension, the application can fail to start and throw a java.lang.IllegalStateException: GlobalOpenTelemetry.set has already been called. error.

Oracle

jdbc:oracle:driver_type:@database_specifier

jdbc:oracle:thin:@localhost:1521/ORCL_SVC

詳しくは 公式ドキュメント をご覧ください。

PostgreSQL

jdbc:postgresql:[//][host][:port][/database][?key=value…​]

jdbc:postgresql://localhost/test

各パートのデフォルトは以下の通り:

host

localhost

port

5432

database

ユーザー名と同じ名前

追加パラメーターの詳細は、公式ドキュメント を参照してください。

Quarkusエクステンションとデータベースドライバーのリファレンス

次の表には、組み込みの db-kind 値、対応する Quarkus エクステンション、およびそれらのエクステンションで使用される JDBC ドライバーが記載されています。

ビルトインデータソースの種類のいずれかを使用する場合、JDBC ドライバーとリアクティブドライバーはこの表の値と一致するように自動的に解決されます。

Table 1. データベースプラットフォームの種類と JDBC ドライバーのマッピング
データベースの種類 Quarkusエクステンション Drivers

db2

quarkus-jdbc-db2

  • JDBC: com.ibm.db2.jcc.DB2Driver

  • XA: com.ibm.db2.jcc.DB2XADataSource

h2

quarkus-jdbc-h2

  • JDBC: org.h2.Driver

  • XA: org.h2.jdbcx.JdbcDataSource

mariadb

quarkus-jdbc-mariadb

  • JDBC: org.mariadb.jdbc.Driver

  • XA: org.mariadb.jdbc.MariaDbDataSource

mssql

quarkus-jdbc-mssql

  • JDBC: com.microsoft.sqlserver.jdbc.SQLServerDriver

  • XA: com.microsoft.sqlserver.jdbc.SQLServerXADataSource

mysql

quarkus-jdbc-mysql

  • JDBC: com.mysql.cj.jdbc.Driver

  • XA: com.mysql.cj.jdbc.MysqlXADataSource

oracle

quarkus-jdbc-oracle

  • JDBC: oracle.jdbc.driver.OracleDriver

  • XA: oracle.jdbc.xa.client.OracleXADataSource

postgresql

quarkus-jdbc-postgresql

  • JDBC: org.postgresql.Driver

  • XA: org.postgresql.xa.PGXADataSource

Table 2. データベースの種類と Reactive ドライバーのマッピング
データベースの種類 Quarkusエクステンション ドライバー

oracle

reactive-oracle-client

io.vertx.oracleclient.spi.OracleDriver

mysql

reactive-mysql-client

io.vertx.mysqlclient.spi.MySQLDriver

mssql

reactive-mssql-client

io.vertx.mssqlclient.spi.MSSQLDriver

postgresql

reactive-pg-client

io.vertx.pgclient.spi.PgDriver

db2

reactive-db2-client

io.vertx.db2client.spi.DB2Driver

この自動解決はほとんどの場合に適用可能であり、ドライバーの設定は必要ありません。

Reactive データソース設定リファレンス

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

quarkus.datasource."datasource-name".reactive

If we create a Reactive datasource for this datasource.

Environment variable: QUARKUS_DATASOURCE_REACTIVE

Show more

boolean

true

quarkus.datasource."datasource-name".reactive.cache-prepared-statements

Whether prepared statements should be cached on the client side.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_CACHE_PREPARED_STATEMENTS

Show more

boolean

true for PostgreSQL/MySQL/MariaDB/Db2, false otherwise

quarkus.datasource."datasource-name".reactive.url

The datasource URLs.

If multiple values are set, this datasource will create a pool with a list of servers instead of a single server. The pool uses round-robin load balancing for server selection during connection establishment. Note that certain drivers might not accommodate multiple values in this context.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_URL

Show more

list of string

quarkus.datasource."datasource-name".reactive.max-size

The datasource pool maximum size.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MAX_SIZE

Show more

int

20

quarkus.datasource."datasource-name".reactive.event-loop-size

When a new connection object is created, the pool assigns it an event loop.

When #event-loop-size is set to a strictly positive value, the pool assigns as many event loops as specified, in a round-robin fashion. By default, the number of event loops configured or calculated by Quarkus is used. If #event-loop-size is set to zero or a negative value, the pool assigns the current event loop to the new connection.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_EVENT_LOOP_SIZE

Show more

int

quarkus.datasource."datasource-name".reactive.trust-all

Whether all server certificates should be trusted.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_ALL

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.trust-certificate-pem

PEM Trust config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_PEM

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.trust-certificate-pem.certs

Comma-separated list of the trust certificate files (Pem format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_PEM_CERTS

Show more

list of string

quarkus.datasource."datasource-name".reactive.trust-certificate-jks

JKS config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_JKS

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.trust-certificate-jks.path

Path of the key file (JKS format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_JKS_PATH

Show more

string

quarkus.datasource."datasource-name".reactive.trust-certificate-jks.password

Password of the key file.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_JKS_PASSWORD

Show more

string

quarkus.datasource."datasource-name".reactive.trust-certificate-pfx

PFX config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_PFX

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.trust-certificate-pfx.path

Path to the key file (PFX format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_PFX_PATH

Show more

string

quarkus.datasource."datasource-name".reactive.trust-certificate-pfx.password

Password of the key.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_TRUST_CERTIFICATE_PFX_PASSWORD

Show more

string

quarkus.datasource."datasource-name".reactive.key-certificate-pem

PEM Key/cert config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PEM

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.key-certificate-pem.keys

Comma-separated list of the path to the key files (Pem format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PEM_KEYS

Show more

list of string

quarkus.datasource."datasource-name".reactive.key-certificate-pem.certs

Comma-separated list of the path to the certificate files (Pem format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PEM_CERTS

Show more

list of string

quarkus.datasource."datasource-name".reactive.key-certificate-jks

JKS config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_JKS

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.key-certificate-jks.path

Path of the key file (JKS format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_JKS_PATH

Show more

string

quarkus.datasource."datasource-name".reactive.key-certificate-jks.password

Password of the key file.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_JKS_PASSWORD

Show more

string

quarkus.datasource."datasource-name".reactive.key-certificate-pfx

PFX config is disabled by default.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PFX

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.key-certificate-pfx.path

Path to the key file (PFX format).

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PFX_PATH

Show more

string

quarkus.datasource."datasource-name".reactive.key-certificate-pfx.password

Password of the key.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_KEY_CERTIFICATE_PFX_PASSWORD

Show more

string

quarkus.datasource."datasource-name".reactive.reconnect-attempts

The number of reconnection attempts when a pooled connection cannot be established on first try.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_RECONNECT_ATTEMPTS

Show more

int

0

quarkus.datasource."datasource-name".reactive.reconnect-interval

The interval between reconnection attempts when a pooled connection cannot be established on first try.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_RECONNECT_INTERVAL

Show more

Duration 

1S

quarkus.datasource."datasource-name".reactive.hostname-verification-algorithm

The hostname verification algorithm to use in case the server’s identity should be checked. Should be HTTPS, LDAPS or NONE. NONE is the default value and disables the verification.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_HOSTNAME_VERIFICATION_ALGORITHM

Show more

string

NONE

quarkus.datasource."datasource-name".reactive.idle-timeout

The maximum time a connection remains unused in the pool before it is closed.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_IDLE_TIMEOUT

Show more

Duration 

no timeout

quarkus.datasource."datasource-name".reactive.max-lifetime

The maximum time a connection remains in the pool, after which it will be closed upon return and replaced as necessary.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MAX_LIFETIME

Show more

Duration 

no timeout

quarkus.datasource."datasource-name".reactive.shared

Set to true to share the pool among datasources. There can be multiple shared pools distinguished by name, when no specific name is set, the __vertx.DEFAULT name is used.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_SHARED

Show more

boolean

false

quarkus.datasource."datasource-name".reactive.name

Set the pool name, used when the pool is shared among datasources, otherwise ignored.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_NAME

Show more

string

quarkus.datasource."datasource-name".reactive.additional-properties."property-key"

Other unspecified properties to be passed through the Reactive SQL Client directly to the database when new connections are initiated.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_ADDITIONAL_PROPERTIES__PROPERTY_KEY_

Show more

Map<String,String>

期間フォーマットについて

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

Reactive DB2 設定

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Datasources

デフォルト

quarkus.datasource."datasource-name".reactive.db2.ssl

Whether SSL/TLS is enabled.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_DB2_SSL

Show more

boolean

false

Reactive MariaDB/MySQL固有の設定

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Additional named datasources

デフォルト

quarkus.datasource."datasource-name".reactive.mysql.charset

Charset for connections.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_CHARSET

Show more

string

quarkus.datasource."datasource-name".reactive.mysql.collation

Collation for connections.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_COLLATION

Show more

string

quarkus.datasource."datasource-name".reactive.mysql.ssl-mode

Desired security state of the connection to the server.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_SSL_MODE

Show more

disabled, preferred, required, verify-ca, verify-identity

disabled

quarkus.datasource."datasource-name".reactive.mysql.connection-timeout

Connection timeout in seconds

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_CONNECTION_TIMEOUT

Show more

int

quarkus.datasource."datasource-name".reactive.mysql.authentication-plugin

The authentication plugin the client should use. By default, it uses the plugin name specified by the server in the initial handshake packet.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_AUTHENTICATION_PLUGIN

Show more

default, mysql-clear-password, mysql-native-password, sha256-password, caching-sha2-password

default

quarkus.datasource."datasource-name".reactive.mysql.pipelining-limit

The maximum number of inflight database commands that can be pipelined. By default, pipelining is disabled.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_PIPELINING_LIMIT

Show more

int

quarkus.datasource."datasource-name".reactive.mysql.use-affected-rows

Whether to return the number of rows matched by the WHERE clause in UPDATE statements, instead of the number of rows actually changed.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MYSQL_USE_AFFECTED_ROWS

Show more

ブーリアン

false

Reactive Microsoft SQLサーバー固有の設定

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Datasources

デフォルト

quarkus.datasource."datasource-name".reactive.mssql.packet-size

The desired size (in bytes) for TDS packets.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MSSQL_PACKET_SIZE

Show more

int

quarkus.datasource."datasource-name".reactive.mssql.ssl

Whether SSL/TLS is enabled.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_MSSQL_SSL

Show more

boolean

false

Reactive Oracle固有の設定

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Datasources

デフォルト

Reactive PostgreSQL固有の設定

ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。

Configuration property

デフォルト

Datasources

デフォルト

quarkus.datasource."datasource-name".reactive.postgresql.pipelining-limit

The maximum number of inflight database commands that can be pipelined.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_POSTGRESQL_PIPELINING_LIMIT

Show more

int

quarkus.datasource."datasource-name".reactive.postgresql.ssl-mode

SSL operating mode of the client.

Environment variable: QUARKUS_DATASOURCE_REACTIVE_POSTGRESQL_SSL_MODE

Show more

disable, allow, prefer, require, verify-ca, verify-full

disable

quarkus.datasource."datasource-name".reactive.postgresql.use-layer7-proxy

Level 7 proxies can load balance queries on several connections to the actual database. When it happens, the client can be confused by the lack of session affinity and unwanted errors can happen like ERROR: unnamed prepared statement does not exist (26000). See Using a level 7 proxy

Environment variable: QUARKUS_DATASOURCE_REACTIVE_POSTGRESQL_USE_LAYER7_PROXY

Show more

boolean

false

Reactive データソースの URL 参照

DB2

db2://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]

db2://dbuser:secretpassword@database.server.com:50000/mydb

現在、クライアントは以下のパラメーターキーをサポートしています。

  • host

  • port

  • user

  • password

  • database

接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。

Microsoft SQL server

sqlserver://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]

sqlserver://dbuser:secretpassword@database.server.com:1433/mydb

現在、クライアントは以下のパラメーターキーをサポートしています。

  • host

  • port

  • user

  • password

  • database

接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。

MySQL / MariaDB

mysql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]

mysql://dbuser:secretpassword@database.server.com:3211/mydb

現在、クライアントは以下のパラメーターキーをサポートしています (大文字と小文字を区別します)。

  • host

  • port

  • user

  • password

  • schema

  • socket

  • useAffectedRows

接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。

Oracle

EZConnect 形式

oracle:thin:@[[protocol:]//]host[:port][/service_name][:server_mode][/instance_name][?connection properties]

oracle:thin:@mydbhost1:5521/mydbservice?connect_timeout=10sec

TNSエイリアス形式

oracle:thin:@<alias_name>[?connection properties]

oracle:thin:@prod_db?TNS_ADMIN=/work/tns/

PostgreSQL

postgresql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]

postgresql://dbuser:secretpassword@database.server.com:5432/mydb

現在、クライアントは以下をサポートしています:

  • 以下のパラメーターキー:

    • host

    • port

    • user

    • password

    • dbname

    • sslmode

  • 次のような追加のプロパティー:

    • application_name

    • fallback_application_name

    • search_path

    • options

接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。

関連コンテンツ