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 データソースの設定
-
選択したデータベースの正しい JDBC エクステンションを追加します。
-
quarkus-jdbc-db2 -
quarkus-jdbc-h2 -
quarkus-jdbc-mariadb -
quarkus-jdbc-mssql -
quarkus-jdbc-mysql -
quarkus-jdbc-oracle -
quarkus-jdbc-postgresql
-
-
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=161 この設定値は、クラスパスに複数のデータベースエクステンションがある場合にのみ必要です。
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データソースの設定
-
選択したデータベースの正しいリアクティブエクステンションを追加します。
-
quarkus-reactive-db2-client -
quarkus-reactive-mssql-client -
quarkus-reactive-mysql-client -
quarkus-reactive-oracle-client -
quarkus-reactive-pg-client
-
-
リアクティブデータソースを設定します:
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=201 この設定値は、クラスパスに複数の Reactive ドライバーエクステンションがある場合にのみ必要です。
データソースの設定
以下のセクションでは、単一または複数のデータソースの設定について説明します。 ここでは簡単のため、単一のデータソースをデフォルトの (無名の) データソースとして参照します。
単一のデータソースの設定
A datasource can be JDBC, reactive, or both. This depends on the configuration and the selection of project extensions.
-
以下の設定プロパティーでデータソースを定義します。
db-kindは、どのデータベースプラットフォームに接続するかを定義します。例えば、h2の場合:quarkus.datasource.db-kind=h2Quarkus derives the JDBC driver class from the
db-kinddatabase 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:
postgresql、pgsql、またはpg -
ビルトインされていない種類のデータベースを使用するには、
otherを使用し、JDBC ドライバーを明示的に定義します。Custom databases and drivers に記載されているように、Quarkus アプリケーションでは、JVM モードで任意の JDBC ドライバーを使用できます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときに、組み込みではないデータベースの種類を使用すると、機能しない可能性があります。
ネイティブ実行可能ファイルをビルドする場合は、利用可能なJDBC Quarkusエクステンションを使用するか、特定のドライバー用にカスタムエクステンションを作成することをお勧めします。
-
-
以下のプロパティーを設定し、クレデンシャルを定義します:
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 と組み合わせて使用する場合に必要となります。
-
To use a JDBC datasource, start by adding the necessary dependencies:
-
組み込みの JDBC ドライバーで使用する場合は、以下のリストからリレーショナルデータベースドライバー用の Quarkus エクステンションを選択して追加します。
-
H2 -
quarkus-jdbc-h2You 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-agroalextension. Agroal provides the JDBC connection pool for built-in and custom JDBC drivers. When you use a custom JDBC driver, addquarkus-agroalexplicitly.
-
-
カスタム JDBC ドライバーと共に使用する場合は、リレーショナルデータベースドライバーのエクステンションと一緒に、
quarkus-agroal依存関係をプロジェクトに追加します:./mvnw quarkus:add-extension -Dextensions="agroal"別のデータベースの JDBC ドライバーを使用するには、use a database with no built-in extension or with a different driver 組み込みのエクステンションがないデータベース、または異なるドライバーを使用するデータベースを利用してください。
-
-
JDBC URL プロパティーを定義して、JDBC 接続を構成します:
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_testNote the
jdbcprefix in the property name. All JDBC-specific configuration properties have thejdbcprefix. For reactive datasources, the prefix isreactive.
JDBC の設定の詳細は、JDBC URL format reference および Quarkus extensions and database drivers reference を参照してください。
カスタムデータベースとドライバー
Quarkus がデータベース用の JDBC エクステンションを提供していない場合、または OpenTelemetry 用などの別の JDBC ドライバーを使用する必要がある場合は、JDBC ドライバーを明示的に設定できます。
エクステンションがない場合、JDBC ドライバーは JVM モードで正しく動作することが期待されます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときには機能しない可能性があります。 ネイティブ実行可能ファイルをビルドするには、既存の Quarkus JDBC エクステンションを使用するか、ドライバー用の新しいエクステンションを提供します。
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には、リアクティブデータソースで使用できるリアクティブクライアントがいくつかあります。
-
対応するエクステンションをアプリケーションに追加します:
-
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と一致している必要があります。
-
-
ドライバーを追加したら、接続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 データソースとリアクティブデータソースの両方を作成しない場合は、次の設定を使用します。
-
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 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].activeをfalseに設定します。
データソースがアクティブでない場合は、以下のようになります。
-
アプリケーションの起動時に、データソースがデータベースに接続しようとしません。
-
データソースは ヘルスチェック を行いません。
-
@Inject DataSource dsや@Inject Pool poolなど、データソースを含む静的 CDI インジェクション・ポイントは、アプリケーションの起動を失敗させます。 -
Dynamic retrieval of the datasource, such as through
CDI.getBeanContainer(),Arc.instance(), or an injectedInstance<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 を設定して 、実行時に永続化ユニットまたはデータソースを選択できます。例えば、
|
この設定では、アクティブな データソースのみにアクセスできるようにします。
これを実現するには、 @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 | DataSource や AgroalDatasource を直接注入しないでください。非アクティブな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 データソースを使用できるようにするには、次の手順を実行します。
-
JDBC ドライバーが XA をサポートしていることを確認してください。 すべての supported JDBC drivers do サポート対象の JDBC ドライバーはサポートしていますが、other JDBC drivers 他の JDBC ドライバーはサポートしていない場合があります。
-
データベースサーバーが XA を有効化するように設定されていることを確認します。
-
Enable XA support explicitly for each relevant datasource by setting
quarkus.datasource[.optional name].jdbc.transactionstoxa.
XA を使用すると、1 つのデータソースでのロールバックにより、トランザクションに登録されている他のすべてのデータソースでのロールバックがトリガーされます。
|
現時点では、リアクティブデータソース上の XA トランザクションはサポートされていません。 |
|
トランザクションにデータソース以外のリソースが含まれる場合は、そのリソースで XA トランザクションがサポートされていない可能性や、追加の設定が必要になる可能性があることに注意してください。 |
1 つのデータソースに対して XA を有効にできない場合:
-
1 つだけを除く すべてのデータソースに対して XA を有効にすることは、Last Resource Commit Optimization (LRCO) を通じて引き続きサポートされている点に注意してください。
-
1 つのデータソースのロールバックによって他のデータソースのロールバックをトリガーする必要がない場合は、コードを複数のトランザクションに分割することを検討してください。 これを行うには、
QuarkusTransaction.requiringNew()/@Transactional(REQUIRES_NEW)(推奨) またはUserTransaction(より複雑なユースケースの場合) を使用します。
|
他の解決策がなく、Quarkus 3.8以前との互換性が必要な場合は、 このプロパティを あるいは、同じように安全でない動作を許可しますが、その際には警告を表示します:
この設定プロパティの使用は推奨しておらず、将来的に削除する予定です。アプリケーションを適宜更新してください。このオプションを維持することが正当な使用例であると考えられる場合は、 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.
統合テストの実行
-
次の Maven コーディネートの下にある追加ツールを提供するアーティファクトに依存関係を追加します。
-
io.quarkus:quarkus-test-h2H2の場合You can test your application even when it is compiled into a native executable, while the database will run as a JVM process.
-
-
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 { }
-
-
マネージドデータベースへの接続を設定します:
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: Show more |
boolean |
|
||
Whether datasource metrics are published in case a metrics extension is present. This is a global setting and is not specific to a datasource.
Environment variable: Show more |
boolean |
|
||
The kind of database we will connect to (e.g. h2, postgresql…). Environment variable: Show more |
string |
|||
The version of the database we will connect to (e.g. '10.0').
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: Show more |
string |
|||
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: Show more |
boolean |
|
||
Whether this datasource should be active at runtime. Environment variable: Show more |
boolean |
|
||
The datasource username Environment variable: Show more |
string |
|||
The datasource password Environment variable: Show more |
string |
|||
The credentials provider name Environment variable: Show more |
string |
|||
The credentials provider bean name. This is a bean name (as in For Vault, the credentials provider bean name is Environment variable: Show more |
string |
|||
型 |
デフォルト |
|||
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: Show more |
boolean |
|||
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
Environment variable: Show more |
string |
|||
Environment variables that are passed to the container. Environment variable: Show more |
Map<String,String> |
|||
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: Show more |
Map<String,String> |
|||
Generic properties that are added to the database connection URL. Environment variable: Show more |
Map<String,String> |
|||
Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly. Environment variable: Show more |
int |
|||
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: Show more |
string |
|||
The database name to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
The username to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
The password to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
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: Show more |
list of string |
|||
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: Show more |
list of string |
|||
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: Show more |
Map<String,String> |
|||
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 configuration property is set to Environment variable: Show more |
boolean |
|
||
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: Show more |
boolean |
|
JDBC 設定リファレンス
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
Activate or disable the dev ui page. Environment variable: Show more |
boolean |
|
Allow sql queries in the Dev UI page Environment variable: Show more |
boolean |
|
Append this to the select done to fetch the table values. eg: LIMIT 100 or TOP 100 Environment variable: 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 Environment variable: Show more |
string |
|
If we create a JDBC datasource for this datasource. Environment variable: Show more |
boolean |
|
The datasource driver class name Environment variable: Show more |
string |
|
Whether we want to use regular JDBC transactions, XA, or disable all transactional capabilities. When enabling XA you will need a driver implementing Environment variable: Show more |
|
|
Enable OpenTelemetry JDBC instrumentation. Environment variable: Show more |
boolean |
|
Enable metrics collection for this datasource. Environment variable: Show more |
boolean |
|
The datasource URL Environment variable: Show more |
string |
|
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: Show more |
int |
|
The datasource pool minimum size Environment variable: Show more |
int |
|
The datasource pool maximum size Environment variable: Show more |
int |
|
The interval at which we validate idle connections in the background. Set to Environment variable: Show more |
|
|
Perform foreground validation on connections that have been idle for longer than the specified interval. Environment variable: Show more |
||
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: Show more |
|
|
The timeout before cancelling the acquisition of a new connection Environment variable: Show more |
|
|
The interval at which we check for connection leaks. Environment variable: Show more |
|
|
The interval at which we try to remove idle connections. Environment variable: Show more |
|
|
The max lifetime of a connection. Environment variable: Show more |
|
|
The transaction isolation level. Environment variable: Show more |
|
|
Collect and display extra troubleshooting info on leaked connections. Environment variable: Show more |
boolean |
|
Allows connections to be flushed upon return to the pool. It’s not enabled by default. Environment variable: Show more |
boolean |
|
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: Show more |
boolean |
|
Query executed when first using a connection. Environment variable: Show more |
string |
|
Query executed to validate a connection. Environment variable: Show more |
string |
|
The timeout for the connection validation query Environment variable: Show more |
||
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 Environment variable: Show more |
boolean |
|
Disable pooling to prevent reuse of Connections. Use this when an external pool manages the life-cycle of Connections. Environment variable: Show more |
boolean |
|
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: Show more |
boolean |
|
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: Show more |
|
|
Other unspecified properties to be passed to the JDBC driver when creating new connections. Environment variable: Show more |
Map<String,String> |
|
Enable OpenTelemetry JDBC instrumentation. Environment variable: Show more |
boolean |
|
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: Show more |
boolean |
|
期間フォーマットについて
期間の値を書くには、標準の 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|
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-opentelemetryextension, the application can fail to start and throw ajava.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 ドライバーとリアクティブドライバーはこの表の値と一致するように自動的に解決されます。
| データベースの種類 | Quarkusエクステンション | Drivers |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| データベースの種類 | Quarkusエクステンション | ドライバー |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
この自動解決はほとんどの場合に適用可能であり、ドライバーの設定は必要ありません。 |
Reactive データソース設定リファレンス
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
If we create a Reactive datasource for this datasource. Environment variable: Show more |
boolean |
|
Whether prepared statements should be cached on the client side. Environment variable: Show more |
boolean |
|
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: Show more |
list of string |
|
The datasource pool maximum size. Environment variable: Show more |
int |
|
When a new connection object is created, the pool assigns it an event loop. When Environment variable: Show more |
int |
|
Whether all server certificates should be trusted. Environment variable: Show more |
boolean |
|
PEM Trust config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the trust certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
PEM Key/cert config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the path to the key files (Pem format). Environment variable: Show more |
list of string |
|
Comma-separated list of the path to the certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
The number of reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
int |
|
The interval between reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
|
|
The hostname verification algorithm to use in case the server’s identity should be checked. Should be Environment variable: Show more |
string |
|
The maximum time a connection remains unused in the pool before it is closed. Environment variable: Show more |
|
|
The maximum time a connection remains in the pool, after which it will be closed upon return and replaced as necessary. Environment variable: Show more |
|
|
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 Environment variable: Show more |
boolean |
|
Set the pool name, used when the pool is shared among datasources, otherwise ignored. Environment variable: Show more |
string |
|
Other unspecified properties to be passed through the Reactive SQL Client directly to the database when new connections are initiated. Environment variable: Show more |
Map<String,String> |
|
期間フォーマットについて
期間の値を書くには、標準の 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|
Reactive DB2 設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
型 |
デフォルト |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Reactive MariaDB/MySQL固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
型 |
デフォルト |
|
Charset for connections. Environment variable: Show more |
string |
|
Collation for connections. Environment variable: Show more |
string |
|
Desired security state of the connection to the server. Environment variable: Show more |
|
|
Connection timeout in seconds Environment variable: Show more |
int |
|
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: Show more |
|
|
The maximum number of inflight database commands that can be pipelined. By default, pipelining is disabled. Environment variable: Show more |
int |
|
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: Show more |
ブーリアン |
|
Reactive Microsoft SQLサーバー固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
型 |
デフォルト |
|
The desired size (in bytes) for TDS packets. Environment variable: Show more |
int |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Reactive Oracle固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
型 |
デフォルト |
Reactive PostgreSQL固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべて実行時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
|---|---|---|
型 |
デフォルト |
|
The maximum number of inflight database commands that can be pipelined. Environment variable: Show more |
int |
|
SSL operating mode of the client. Environment variable: Show more |
|
|
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: Show more |
boolean |
|
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
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 でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。 |