Hibernate Reactiveの使用
Hibernate Reactiveは、Hibernate ORMのリアクティブAPIで、ノンブロッキングのデータベースドライバと、データベースとのインタラクションのリアクティブなスタイルをサポートしています。
Hibernate Reactiveは、 Hibernate ORMガイド で説明されている同じアノテーションと、ほとんどの設定で動作します。このガイドでは、Hibernate Reactiveに特有のものにのみ焦点を当てます。 |
ソリューション
次のセクションで紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。
Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.git
、 アーカイブ をダウンロードします。
ソリューションは hibernate-reactive-quickstart
ディレクトリにあります。
Hibernate Reactiveのセットアップと設定
QuarkusでHibernate Reactiveを使用する場合、以下が必要です:
-
application.properties
に設定を追加 -
エンティティに
@Entity
やその他のマッピングアノテーションを通常通り付与
その他の設定の必要性は自動化されています。Quarkusは、いくつかの定見に基づいた選択と経験に基づいた推測を行います。
以下の依存関係をプロジェクトに追加してください:
-
Hibernate Reactive エクステンション:
io.quarkus:quarkus-hibernate-reactive
-
選択したデータベース用の Reactive SQLクライアントエクステンション。以下のオプションが利用できます:
-
quarkus-reactive-pg-client
: PostgreSQLやCockroachDBのクライアント -
quarkus-reactive-mysql-client
: MySQL または MariaDBのクライアント -
quarkus-reactive-mssql-client
: Microsoft SQL Server のクライアント -
quarkus-reactive-db2-client
: IBM Db2 のクライアント -
quarkus-reactive-oracle-client
: Oracleのクライアント
-
例えば
<!-- Hibernate Reactive dependency -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-reactive</artifactId>
</dependency>
<!-- Reactive SQL client for PostgreSQL -->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-reactive-pg-client</artifactId>
</dependency>
// Hibernate Reactive dependency
implementation("io.quarkus:quarkus-hibernate-reactive")
Reactive SQL client for PostgreSQL
implementation("io.quarkus:quarkus-reactive-pg-client")
@Entity
でパーシステント・オブジェクトにアノテーションを付け、 application.properties
で関連する構成プロパティを追加します。
application.properties
# datasource configuration
quarkus.datasource.db-kind = postgresql
quarkus.datasource.username = quarkus_test
quarkus.datasource.password = quarkus_test
quarkus.datasource.reactive.url = vertx-reactive:postgresql://localhost/quarkus_test (1)
# drop and create the database at startup (use `update` to only update the schema)
quarkus.hibernate-orm.database.generation=drop-and-create
1 | Hibernate ORMの設定と唯一異なるプロパティ |
これらの設定プロパティは、典型的なHibernate Reactive設定ファイルにあるものと同じではないことに注意してください。これらはしばしばHibernate Reactive設定プロパティにマッピングされますが、名前が異なる可能性があり、必ずしも1対1でマッピングされるわけではありません。
また、Quarkusは多くのHibernate Reactiveの設定を自動的に行い、より現代的なデフォルトを使用することが多いです。
標準の persistence.xml 設定ファイルを使用してHibernate Reactiveを設定することはサポートされていません。
|
application.properties
で設定できるプロパティのリストについては、Hibernate Reactive 設定プロパティ のセクションを参照してください。
プロジェクトの依存関係の中にHibernate Reactiveエクステンションがリストアップされていれば、Quarkus datasource
の設定に基づいて Mutiny.SessionFactory
が作成されます。
dialectは、Reactive SQLクライアントに基づいて選択されます(明示的に設定しない限り)。
その後、 Mutiny.SessionFactory
を注入することができます。
@ApplicationScoped
public class SantaClausService {
@Inject
Mutiny.SessionFactory sf; (1)
public Uni<Void> createGift(String giftDescription) {
Gift gift = new Gift();
gift.setName(giftDescription);
return sf.withTransaction(session -> session.persist(gift)) (2)
}
}
1 | セッションファクトリを注入して楽しもう |
2 | .withTransaction() はコミット時に自動的にフラッシュされます。 |
データベースを変更するメソッド(例: session.persist(entity) )は、必ずトランザクション内にラップしてください。
|
@Entity
public class Gift {
private Long id;
private String name;
@Id
@SequenceGenerator(name = "giftSeq", sequenceName = "gift_id_seq", allocationSize = 1, initialValue = 1)
@GeneratedValue(generator = "giftSeq")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hibernate Reactive の起動時に SQL 文をロードするには、 src/main/resources/
ディレクトリに import.sql
ファイルを追加します。このスクリプトには、任意の SQL DML ステートメントを含めることができます。各ステートメントは必ずセミコロンで終了させてください。
テストやデモ用のデータセットを用意しておくと便利です。
Hibernate Reactiveの設定プロパティ
セッションファクトリを改良したり、Quarkusの推測を導くのに役立つ様々なオプションのプロパティがあります。
プロパティが設定されていない場合、Quarkusは通常、Hibernate Reactiveのセットアップに必要なすべてを推測し、デフォルトのデータソースを使用するようにします。
ここに記載されている設定プロパティーでは、このようなデフォルトを上書きしたり、様々な面をカスタマイズしたり調整したりすることができます。
Hibernate Reactiveでは、Hibernate ORMで使用するのと同じプロパティを使用します。いくつかのプロパティの名前に jdbc
が含まれていることに気づくと思いますが、Hibernate Reactive には JDBC は存在せず、これらは単に従来のプロパティ名です。
ビルド時に固定される設定プロパティ - その他の設定プロパティはランタイムでオーバーライド可能です。
型 |
デフォルト |
|||
---|---|---|---|---|
Whether Hibernate ORM is enabled during the build. If Hibernate ORM is disabled during the build, all processing related to Hibernate ORM will be skipped,
but it will not be possible to activate Hibernate ORM at runtime:
Environment variable: |
boolean |
|
||
Environment variable: |
string |
|||
Environment variable: |
list of string |
|||
Path to a file containing the SQL statements to execute when Hibernate ORM starts. The file is retrieved from the classpath resources,
so it must be located in the resources directory (e.g. The default value for this setting differs depending on the Quarkus launch mode:
If you need different SQL statements between dev mode, test ( application.properties
Environment variable: |
list of string |
|
||
Pluggable strategy contract for applying physical naming rules for database object names. Class name of the Hibernate PhysicalNamingStrategy implementation Environment variable: |
string |
|||
Pluggable strategy for applying implicit naming rules when an explicit name is not given. Class name of the Hibernate ImplicitNamingStrategy implementation Environment variable: |
string |
|||
Class name of a custom
Environment variable: |
string |
|||
XML files to configure the entity mapping, e.g. Environment variable: |
list of string |
|
||
The default in Quarkus is for 2nd level caching to be enabled, and a good implementation is already integrated for you. Just cherry-pick which entities should be using the cache. Set this to false to disable all 2nd level caches. Environment variable: |
boolean |
|
||
Defines the method for multi-tenancy (DATABASE, NONE, SCHEMA). The complete list of allowed values is available in the Hibernate ORM JavaDoc. The type DISCRIMINATOR is currently not supported. The default value is NONE (no multi-tenancy). Environment variable: |
string |
|||
Defines the name of the datasource to use in case of SCHEMA approach. The datasource of the persistence unit will be used if not set. Environment variable: |
string |
|||
If hibernate is not auto generating the schema, and Quarkus is running in development mode then Quarkus will attempt to validate the database after startup and print a log message if there are any problems. Environment variable: |
boolean |
|
||
Whether statistics collection is enabled. If 'metrics.enabled' is true, then the default here is considered true, otherwise the default is false. Environment variable: |
boolean |
|||
Whether session metrics should be appended into the server log for each Hibernate session. This only has effect if statistics are enabled ( Environment variable: |
boolean |
|||
Whether metrics are published if a metrics extension is enabled. Environment variable: |
boolean |
|
||
Whether this persistence unit should be active at runtime. If the persistence unit is not active, it won’t start with the application, and accessing the corresponding EntityManagerFactory/EntityManager or SessionFactory/Session will not be possible. Note that if Hibernate ORM is disabled (i.e. Environment variable: |
boolean |
|
||
Properties that should be passed on directly to Hibernate ORM.
Use the full configuration property key here,
for instance
Consider using a supported configuration property before falling back to unsupported ones. If none exists, make sure to file a feature request so that a supported configuration property can be added to Quarkus, and more importantly so that the configuration property is tested regularly. Environment variable: |
|
|||
型 |
デフォルト |
|||
Class name of the Hibernate ORM dialect. The complete list of bundled dialects is available in the Hibernate ORM JavaDoc.
Environment variable: |
string |
|||
The storage engine to use when the dialect supports multiple storage engines. E.g. Environment variable: |
string |
|||
型 |
デフォルト |
|||
The maximum size of the query plan cache. see # Environment variable: |
int |
|
||
Default precedence of null values in Valid values are: Environment variable: |
|
|
||
Enables IN clause parameter padding which improves statement caching. Environment variable: |
boolean |
|
||
型 |
デフォルト |
|||
The charset of the database. Used for DDL generation and also for the SQL import scripts. Environment variable: |
|
|||
Whether Hibernate should quote all identifiers. Environment variable: |
boolean |
|
||
Select whether the database schema is generated or not. Environment variable: |
string |
|
||
If Hibernate ORM should create the schemas automatically (for databases supporting them). Environment variable: |
boolean |
|
||
Whether we should stop on the first error when applying the schema. Environment variable: |
boolean |
|
||
The default catalog to use for the database objects. Environment variable: |
string |
|||
The default schema to use for the database objects. Environment variable: |
string |
|||
型 |
デフォルト |
|||
The time zone pushed to the JDBC driver. Environment variable: |
string |
|||
How many rows are fetched at a time by the JDBC driver. Environment variable: |
int |
|||
The number of updates (inserts, updates and deletes) that are sent by the JDBC driver at one time for execution. Environment variable: |
int |
|||
型 |
デフォルト |
|||
The size of the batches used when loading entities and collections.
Environment variable: |
int |
|
||
The maximum depth of outer join fetch tree for single-ended associations (one-to-one, many-to-one). A Environment variable: |
int |
|||
型 |
デフォルト |
|||
The maximum time before an object of the cache is considered expired. Environment variable: |
||||
The maximum number of objects kept in memory in the cache. Environment variable: |
長 |
|||
型 |
デフォルト |
|||
Existing applications rely (implicitly or explicitly) on Hibernate ignoring any DiscriminatorColumn declarations on joined inheritance hierarchies. This setting allows these applications to maintain the legacy behavior of DiscriminatorColumn annotations being ignored when paired with joined inheritance. Environment variable: |
boolean |
|
||
型 |
デフォルト |
|||
Environment variable: |
string |
|||
Environment variable: |
list of string |
|||
Path to a file containing the SQL statements to execute when Hibernate ORM starts. The file is retrieved from the classpath resources,
so it must be located in the resources directory (e.g. The default value for this setting differs depending on the Quarkus launch mode:
If you need different SQL statements between dev mode, test ( application.properties
Environment variable: |
list of string |
|
||
Pluggable strategy contract for applying physical naming rules for database object names. Class name of the Hibernate PhysicalNamingStrategy implementation Environment variable: |
string |
|||
Pluggable strategy for applying implicit naming rules when an explicit name is not given. Class name of the Hibernate ImplicitNamingStrategy implementation Environment variable: |
string |
|||
Class name of a custom
Environment variable: |
string |
|||
XML files to configure the entity mapping, e.g. Environment variable: |
list of string |
|
||
The default in Quarkus is for 2nd level caching to be enabled, and a good implementation is already integrated for you. Just cherry-pick which entities should be using the cache. Set this to false to disable all 2nd level caches. Environment variable: |
boolean |
|
||
Defines the method for multi-tenancy (DATABASE, NONE, SCHEMA). The complete list of allowed values is available in the Hibernate ORM JavaDoc. The type DISCRIMINATOR is currently not supported. The default value is NONE (no multi-tenancy). Environment variable: |
string |
|||
Defines the name of the datasource to use in case of SCHEMA approach. The datasource of the persistence unit will be used if not set. Environment variable: |
string |
|||
If hibernate is not auto generating the schema, and Quarkus is running in development mode then Quarkus will attempt to validate the database after startup and print a log message if there are any problems. Environment variable: |
boolean |
|
||
Whether this persistence unit should be active at runtime. If the persistence unit is not active, it won’t start with the application, and accessing the corresponding EntityManagerFactory/EntityManager or SessionFactory/Session will not be possible. Note that if Hibernate ORM is disabled (i.e. Environment variable: |
boolean |
|
||
Properties that should be passed on directly to Hibernate ORM.
Use the full configuration property key here,
for instance
Consider using a supported configuration property before falling back to unsupported ones. If none exists, make sure to file a feature request so that a supported configuration property can be added to Quarkus, and more importantly so that the configuration property is tested regularly. Environment variable: |
|
|||
型 |
デフォルト |
|||
Class name of the Hibernate ORM dialect. The complete list of bundled dialects is available in the Hibernate ORM JavaDoc.
Environment variable: |
string |
|||
The storage engine to use when the dialect supports multiple storage engines. E.g. Environment variable: |
string |
|||
型 |
デフォルト |
|||
The maximum size of the query plan cache. see # Environment variable: |
int |
|
||
Default precedence of null values in Valid values are: Environment variable: |
|
|
||
Enables IN clause parameter padding which improves statement caching. Environment variable: |
boolean |
|
||
型 |
デフォルト |
|||
The charset of the database. Used for DDL generation and also for the SQL import scripts. Environment variable: |
|
|||
Whether Hibernate should quote all identifiers. Environment variable: |
boolean |
|
||
Select whether the database schema is generated or not. Environment variable: |
string |
|
||
If Hibernate ORM should create the schemas automatically (for databases supporting them). Environment variable: |
boolean |
|
||
Whether we should stop on the first error when applying the schema. Environment variable: |
boolean |
|
||
The default catalog to use for the database objects. Environment variable: |
string |
|||
The default schema to use for the database objects. Environment variable: |
string |
|||
型 |
デフォルト |
|||
The time zone pushed to the JDBC driver. Environment variable: |
string |
|||
How many rows are fetched at a time by the JDBC driver. Environment variable: |
int |
|||
The number of updates (inserts, updates and deletes) that are sent by the JDBC driver at one time for execution. Environment variable: |
int |
|||
型 |
デフォルト |
|||
The size of the batches used when loading entities and collections.
Environment variable: |
int |
|
||
The maximum depth of outer join fetch tree for single-ended associations (one-to-one, many-to-one). A Environment variable: |
int |
|||
型 |
デフォルト |
|||
The maximum time before an object of the cache is considered expired. Environment variable: |
||||
The maximum number of objects kept in memory in the cache. Environment variable: |
長 |
|||
型 |
デフォルト |
|||
Existing applications rely (implicitly or explicitly) on Hibernate ignoring any DiscriminatorColumn declarations on joined inheritance hierarchies. This setting allows these applications to maintain the legacy behavior of DiscriminatorColumn annotations being ignored when paired with joined inheritance. Environment variable: |
boolean |
|
||
型 |
デフォルト |
|||
Select whether the database schema DDL files are generated or not. Accepted values: Environment variable: |
string |
|
||
Filename or URL where the database create DDL file should be generated. Environment variable: |
string |
|||
Filename or URL where the database drop DDL file should be generated. Environment variable: |
string |
|||
型 |
デフォルト |
|||
Show SQL logs and format them nicely. Setting it to true is obviously not recommended in production. Environment variable: |
boolean |
|
||
Format the SQL logs if SQL log is enabled Environment variable: |
boolean |
|
||
Whether JDBC warnings should be collected and logged. Environment variable: |
boolean |
|
||
If set, Hibernate will log queries that took more than specified number of milliseconds to execute. Environment variable: |
長 |
|||
型 |
デフォルト |
|||
Logs SQL bind parameters. Setting it to true is obviously not recommended in production. Environment variable: |
boolean |
|
||
Show SQL logs and format them nicely. Setting it to true is obviously not recommended in production. Environment variable: |
boolean |
|
||
Format the SQL logs if SQL log is enabled Environment variable: |
boolean |
|
||
Whether JDBC warnings should be collected and logged. Environment variable: |
boolean |
|
||
If set, Hibernate will log queries that took more than specified number of milliseconds to execute. Environment variable: |
長 |
|||
型 |
デフォルト |
|||
Select whether the database schema DDL files are generated or not. Accepted values: Environment variable: |
string |
|
||
Filename or URL where the database create DDL file should be generated. Environment variable: |
string |
|||
Filename or URL where the database drop DDL file should be generated. Environment variable: |
string |
期間フォーマットについて
期間のフォーマットは標準の 数値で始まる期間の値を指定することもできます。この場合、値が数値のみで構成されている場合、コンバーターは値を秒として扱います。そうでない場合は、 |
PostgreSQLサーバをDockerで起動したいですか?
これは、永続化されない空のデータベースを起動します。簡単な実験に最適です! |
テスト
Using Hibernate Reactive in a @QuarkusTest
is slightly more involved than using Hibernate ORM due to the asynchronous nature of the APIs and the fact that all operations need to run on a Vert.x Event Loop.
Two components are necessary to write these tests:
-
The use of
@io.quarkus.test.vertx.RunOnVertxContext
or@io.quarkus.test.TestReactiveTransaction
on the test methods -
The use of
io.quarkus.test.vertx.UniAsserter
as a test method parameter.
These classes are provided by the quarkus-test-vertx dependency.
|
A very simple example usage looks like:
@QuarkusTest
public class SomeTest {
@Inject
Mutiny.SessionFactory sessionFactory;
@Test
@RunOnVertxContext
public void testQuery(UniAsserter asserter) {
asserter.assertThat(() -> sessionFactory.withSession(s -> s.createQuery(
"from Gift g where g.name = :name").setParameter("name", "Lego").getResultList()),
list -> org.junit.jupiter.api.Assertions.assertEquals(list.size(), 1));
}
}
See the Javadoc of UniAsserter for a full description of the various methods that can be used for creating assertions.
|
制限事項など知っておくべきこと
Quarkusは使用しているライブラリを修正しません。このルールはHibernate Reactiveにも適用されます。このエクステンションを使用すると、ほとんどの場合、元のライブラリを使用するのと同じ経験ができます。
しかし、両者は同じコードを共有していますが、Quarkusはいくつかのコンポーネントを自動的に設定し、いくつかの拡張ポイントにカスタム実装を注入しています。
ここでは、QuarkusでHibernate Reactiveを使用する際に注意すべき点を紹介します。
-
現時点では、複数の永続化ユニットを設定することはできません。
-
persistence.xml
のファイルでは設定できません。 -
Enversエクステンションとの統合はサポートされていません。
-
javax.transaction.Transactional
を使用して、トランザクション境界を行うことはできません。
PanacheでHibernate Reactiveをシンプルに
Hibernate Reactive with Panacheエクステンションは、Active Recordスタイルのエンティティ(およびリポジトリ)を提供することで、Hibernate Reactiveの使用を促進し、Quarkusでエンティティを簡単に楽しく書けるようにすることに重点を置いています。