The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Hibernate Reactiveの使用

Hibernate Reactiveは、Hibernate ORMのリアクティブAPIで、ノンブロッキングのデータベースドライバと、データベースとのインタラクションのリアクティブなスタイルをサポートしています。

Hibernate Reactiveは、 Hibernate ORM の置き換えでも、Hibernate ORMの将来でもありません。これは、高い並行性が必要なリアクティブなユースケース向けに調整された別のスタックです。

また、デフォルトのRESTレイヤであるQuarkus REST(旧RESTEasy Reactive)を使用する場合、Hibernate Reactiveを使用する必要はありません。 Quarkus RESTとHibernate ORMを併用することはまったく問題ありません。 高い同時性が必要ない場合やリアクティブパラダイムに慣れていない場合は、Hibernate ORMを使用することをお勧めします。

Hibernate Reactiveは、 Hibernate ORMガイド で説明されている同じアノテーションと、ほとんどの設定で動作します。このガイドでは、Hibernate Reactiveに特有のものにのみ焦点を当てます。

この技術は、previewと考えられています。

preview では、下位互換性やエコシステムでの存在は保証されていません。具体的な改善には設定や API の変更が必要になるかもしれませんが、 stable になるための計画は現在進行中です。フィードバックは メーリングリストGitHub の課題管理 で受け付けています。

とりうるステータスの完全なリストについては、 FAQの項目 を参照してください。

ソリューション

次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。

Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.gitアーカイブ をダウンロードします。

ソリューションは hibernate-reactive-quickstart ディレクトリ にあります。

Hibernate Reactiveのセットアップと設定

QuarkusでHibernate Reactiveを使用する場合、以下が必要です:

  • application.properties に設定を追加

  • エンティティに @Entity やその他のマッピングアノテーションを通常通り付与

その他の設定の必要性は自動化されています。Quarkusは、いくつかの定見に基づいた選択と経験に基づいた推測を行います。

以下の依存関係をプロジェクトに追加してください:

例えば

pom.xml
<!-- 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>
build.gradle
// 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 を注入することができます。

Hibernate Reactiveを使用したアプリケーションBeanの例
@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 は存在せず、これらは単に従来のプロパティ名です。

ビルド時に固定される構成プロパティ - 他のすべての構成プロパティは実行時にオーバーライド可能

Configuration property

デフォルト

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: quarkus.hibernate-orm.active will default to false and setting it to true will lead to an error.

Environment variable: QUARKUS_HIBERNATE_ORM_ENABLED

Show more

boolean

true

If true, Quarkus will ignore any persistence.xml file in the classpath and rely exclusively on the Quarkus configuration.

Environment variable: QUARKUS_HIBERNATE_ORM_PERSISTENCE_XML_IGNORE

Show more

boolean

false

Whether statistics collection is enabled. If 'metrics.enabled' is true, then the default here is considered true, otherwise the default is false.

Environment variable: QUARKUS_HIBERNATE_ORM_STATISTICS

Show more

boolean

Whether session metrics should be appended into the server log for each Hibernate session. This only has effect if statistics are enabled (quarkus.hibernate-orm.statistics). The default is false (which means both statistics and log-session-metrics need to be enabled for the session metrics to appear in the log).

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_SESSION_METRICS

Show more

boolean

Whether metrics are published if a metrics extension is enabled.

Environment variable: QUARKUS_HIBERNATE_ORM_METRICS_ENABLED

Show more

boolean

false

The name of the datasource which this persistence unit uses.

If undefined, it will use the default datasource.

Environment variable: QUARKUS_HIBERNATE_ORM_DATASOURCE

Show more

string

The packages in which the entities affected to this persistence unit are located.

Environment variable: QUARKUS_HIBERNATE_ORM_PACKAGES

Show more

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. src/main/resources).

The default value for this setting differs depending on the Quarkus launch mode:

  • In dev and test modes, it defaults to import.sql. Simply add an import.sql file in the root of your resources directory and it will be picked up without having to set this property. Pass no-file to force Hibernate ORM to ignore the SQL import file.

  • In production mode, it defaults to no-file. It means Hibernate ORM won’t try to execute any SQL import file by default. Pass an explicit value to force Hibernate ORM to execute the SQL import file.

If you need different SQL statements between dev mode, test (@QuarkusTest) and in production, use Quarkus configuration profiles facility.

application.properties
%dev.quarkus.hibernate-orm.sql-load-script = import-dev.sql
%test.quarkus.hibernate-orm.sql-load-script = import-test.sql
%prod.quarkus.hibernate-orm.sql-load-script = no-file

Quarkus supports .sql file with SQL statements or comments spread over multiple lines. Each SQL statement must be terminated by a semicolon.

Environment variable: QUARKUS_HIBERNATE_ORM_SQL_LOAD_SCRIPT

Show more

list of String

import.sql in DEV, TEST ; no-file otherwise

Pluggable strategy contract for applying physical naming rules for database object names. Class name of the Hibernate PhysicalNamingStrategy implementation

Environment variable: QUARKUS_HIBERNATE_ORM_PHYSICAL_NAMING_STRATEGY

Show more

string

Pluggable strategy for applying implicit naming rules when an explicit name is not given. Class name of the Hibernate ImplicitNamingStrategy implementation

Environment variable: QUARKUS_HIBERNATE_ORM_IMPLICIT_NAMING_STRATEGY

Show more

string

Class name of a custom org.hibernate.boot.spi.MetadataBuilderContributor implementation.

Not all customization options exposed by org.hibernate.boot.MetadataBuilder will work correctly. Stay clear of options related to classpath scanning in particular.

This setting is exposed mainly to allow registration of types, converters and SQL functions.

Environment variable: QUARKUS_HIBERNATE_ORM_METADATA_BUILDER_CONTRIBUTOR

Show more

string

XML files to configure the entity mapping, e.g. META-INF/my-orm.xml.

Defaults to META-INF/orm.xml if it exists. Pass no-file to force Hibernate ORM to ignore META-INF/orm.xml.

Environment variable: QUARKUS_HIBERNATE_ORM_MAPPING_FILES

Show more

list of String

META-INF/orm.xml if it exists; no-file otherwise

Identifiers can be quoted using one of the available strategies.

Set to none by default, meaning no identifiers will be quoted. If set to all, all identifiers and column definitions will be quoted. Additionally, setting it to all-except-column-definitions will skip the column definitions, which can usually be required when they exist, or else use the option only-keywords to quote only identifiers deemed SQL keywords by the Hibernate ORM dialect.

Environment variable: QUARKUS_HIBERNATE_ORM_QUOTE_IDENTIFIERS_STRATEGY

Show more

none, all, all-except-column-definitions, only-keywords

none

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: QUARKUS_HIBERNATE_ORM_SECOND_LEVEL_CACHING_ENABLED

Show more

boolean

true

Enables the Bean Validation integration.

Environment variable: QUARKUS_HIBERNATE_ORM_VALIDATION_ENABLED

Show more

boolean

true

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: QUARKUS_HIBERNATE_ORM_MULTITENANT

Show more

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: QUARKUS_HIBERNATE_ORM_MULTITENANT_SCHEMA_DATASOURCE

Show more

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: QUARKUS_HIBERNATE_ORM_VALIDATE_IN_DEV_MODE

Show more

boolean

true

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. quarkus.hibernate-orm.enabled is set to false), all persistence units are deactivated, and setting this property to true will fail.

Environment variable: QUARKUS_HIBERNATE_ORM_ACTIVE

Show more

boolean

'true' if Hibernate ORM is enabled; 'false' otherwise

Properties that should be passed on directly to Hibernate ORM. Use the full configuration property key here, for instance quarkus.hibernate-orm.unsupported-properties."hibernate.order_inserts" = true.

Properties set here are completely unsupported: as Quarkus doesn’t generally know about these properties and their purpose, there is absolutely no guarantee that they will work correctly, and even if they do, that may change when upgrading to a newer version of Quarkus (even just a micro/patch version).

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: QUARKUS_HIBERNATE_ORM_UNSUPPORTED_PROPERTIES

Show more

Map<String,String>

Dialect related configuration

デフォルト

Class name of the Hibernate ORM dialect.

The complete list of bundled dialects is available in the Hibernate ORM JavaDoc.

Setting the dialect directly is only recommended as a last resort: most popular databases have a corresponding Quarkus extension, allowing Quarkus to select the dialect automatically, in which case you do not need to set the dialect at all, though you may want to set quarkus.datasource.db-version as high as possible to benefit from the best performance and latest features.

If your database does not have a corresponding Quarkus extension, you will need to set the dialect directly. In that case, keep in mind that the JDBC driver and Hibernate ORM dialect may not work properly in GraalVM native executables.

Environment variable: QUARKUS_HIBERNATE_ORM_DIALECT

Show more

string

selected automatically for most popular databases

The storage engine to use when the dialect supports multiple storage engines.

E.g. MyISAM or InnoDB for MySQL.

Environment variable: QUARKUS_HIBERNATE_ORM_DIALECT_STORAGE_ENGINE

Show more

string

Mapping configuration

デフォルト

How to store timezones in the database by default for properties of type OffsetDateTime and ZonedDateTime.

This default may be overridden on a per-property basis using @TimeZoneStorage.

Properties of type OffsetTime are not affected by this setting.
default

Equivalent to native if supported, normalize-utc otherwise.

auto

Equivalent to native if supported, column otherwise.

native

Stores the timestamp and timezone in a column of type timestamp with time zone.

Only available on some databases/dialects; if not supported, an exception will be thrown during static initialization.

column

Stores the timezone in a separate column next to the timestamp column.

Use @TimeZoneColumn on the relevant entity property to customize the timezone column.

normalize-utc

Does not store the timezone, and loses timezone information upon persisting.

Instead, normalizes the value to a timestamp in the UTC timezone.

normalize

Does not store the timezone, and loses timezone information upon persisting.

Instead, normalizes the value: * upon persisting to the database, to a timestamp in the JDBC timezone set through quarkus.hibernate-orm.jdbc.timezone, or the JVM default timezone if not set. * upon reading back from the database, to the JVM default timezone.

+ Use this to get the legacy behavior of Quarkus 2 / Hibernate ORM 5 or older.

Environment variable: QUARKUS_HIBERNATE_ORM_MAPPING_TIMEZONE_DEFAULT_STORAGE

Show more

native, normalize, normalize-utc, column, auto, default

default

The optimizer to apply to identifier generators whose optimizer is not configured explicitly.

Only relevant for table- and sequence-based identifier generators. Other generators, such as UUID-based generators, will ignore this setting.

The optimizer is responsible for pooling new identifier values, in order to reduce the frequency of database calls to retrieve those values and thereby improve performance.

Environment variable: QUARKUS_HIBERNATE_ORM_MAPPING_ID_OPTIMIZER_DEFAULT

Show more

pooled-lo, pooled, none

pooled-lo

Query related configuration

デフォルト

The maximum size of the query plan cache. see #org.hibernate.cfg.AvailableSettings#QUERY_PLAN_CACHE_MAX_SIZE

Environment variable: QUARKUS_HIBERNATE_ORM_QUERY_QUERY_PLAN_CACHE_MAX_SIZE

Show more

int

2048

Default precedence of null values in ORDER BY clauses.

Valid values are: none, first, last.

Environment variable: QUARKUS_HIBERNATE_ORM_QUERY_DEFAULT_NULL_ORDERING

Show more

none, first, last

none

Enables IN clause parameter padding which improves statement caching.

Environment variable: QUARKUS_HIBERNATE_ORM_QUERY_IN_CLAUSE_PARAMETER_PADDING

Show more

boolean

true

JDBC related configuration

デフォルト

The time zone pushed to the JDBC driver. See quarkus.hibernate-orm.mapping.timezone.default-storage.

Environment variable: QUARKUS_HIBERNATE_ORM_JDBC_TIMEZONE

Show more

string

How many rows are fetched at a time by the JDBC driver.

Environment variable: QUARKUS_HIBERNATE_ORM_JDBC_STATEMENT_FETCH_SIZE

Show more

int

The number of updates (inserts, updates and deletes) that are sent by the JDBC driver at one time for execution.

Environment variable: QUARKUS_HIBERNATE_ORM_JDBC_STATEMENT_BATCH_SIZE

Show more

int

Fetching logic configuration

デフォルト

The size of the batches used when loading entities and collections.

-1 means batch loading is disabled.

Environment variable: QUARKUS_HIBERNATE_ORM_FETCH_BATCH_SIZE

Show more

int

16

The maximum depth of outer join fetch tree for single-ended associations (one-to-one, many-to-one).

A 0 disables default outer join fetching.

Environment variable: QUARKUS_HIBERNATE_ORM_FETCH_MAX_DEPTH

Show more

int

Caching configuration

デフォルト

The maximum time before an object of the cache is considered expired.

Environment variable: QUARKUS_HIBERNATE_ORM_CACHE__CACHE__EXPIRATION_MAX_IDLE

Show more

Duration

The maximum number of objects kept in memory in the cache.

Environment variable: QUARKUS_HIBERNATE_ORM_CACHE__CACHE__MEMORY_OBJECT_COUNT

Show more

Discriminator related configuration

デフォルト

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: QUARKUS_HIBERNATE_ORM_DISCRIMINATOR_IGNORE_EXPLICIT_FOR_JOINED

Show more

boolean

false

Database related configuration

デフォルト

When set, attempts to exchange data with the database as the given version of Hibernate ORM would have, on a best-effort basis.

Please note:

  • schema validation may still fail in some cases: this attempts to make Hibernate ORM 6+ behave correctly at runtime, but it may still expect a different (but runtime-compatible) schema.

  • robust test suites are still useful and recommended: you should still check that your application behaves as intended with your legacy schema.

  • this feature is inherently unstable: some aspects of it may stop working in future versions of Quarkus, and older versions will be dropped as Hibernate ORM changes pile up and support for those older versions becomes too unreliable.

  • you should still plan a migration of your schema to a newer version of Hibernate ORM. For help with migration, refer to the Quarkus 3 migration guide from Hibernate ORM 5 to 6.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_ORM_COMPATIBILITY_VERSION

Show more

5.6, latest

latest

The charset of the database.

Used for DDL generation and also for the SQL import scripts.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_CHARSET

Show more

Charset

UTF-8

Select whether the database schema is generated or not. drop-and-create is awesome in development mode. This defaults to 'none', however if Dev Services is in use and no other extensions that manage the schema are present this will default to 'drop-and-create'. Accepted values: none, create, drop-and-create, drop, update, validate.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_GENERATION

Show more

String

none

If Hibernate ORM should create the schemas automatically (for databases supporting them).

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_GENERATION_CREATE_SCHEMAS

Show more

boolean

false

Whether we should stop on the first error when applying the schema.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_GENERATION_HALT_ON_ERROR

Show more

boolean

false

The default catalog to use for the database objects.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_DEFAULT_CATALOG

Show more

string

The default schema to use for the database objects.

Environment variable: QUARKUS_HIBERNATE_ORM_DATABASE_DEFAULT_SCHEMA

Show more

string

Database scripts related configuration

デフォルト

Select whether the database schema DDL files are generated or not. Accepted values: none, create, drop-and-create, drop, update, validate.

Environment variable: QUARKUS_HIBERNATE_ORM_SCRIPTS_GENERATION

Show more

String

none

Filename or URL where the database create DDL file should be generated.

Environment variable: QUARKUS_HIBERNATE_ORM_SCRIPTS_GENERATION_CREATE_TARGET

Show more

string

Filename or URL where the database drop DDL file should be generated.

Environment variable: QUARKUS_HIBERNATE_ORM_SCRIPTS_GENERATION_DROP_TARGET

Show more

string

Logging configuration

デフォルト

Logs SQL bind parameters.

Setting it to true is obviously not recommended in production.

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_BIND_PARAMETERS

Show more

boolean

false

Show SQL logs and format them nicely.

Setting it to true is obviously not recommended in production.

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_SQL

Show more

boolean

false

Format the SQL logs if SQL log is enabled

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_FORMAT_SQL

Show more

boolean

true

Whether JDBC warnings should be collected and logged.

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_JDBC_WARNINGS

Show more

boolean

depends on dialect

If set, Hibernate will log queries that took more than specified number of milliseconds to execute.

Environment variable: QUARKUS_HIBERNATE_ORM_LOG_QUERIES_SLOWER_THAN_MS

Show more

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

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

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

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

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

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

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

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

PostgreSQLサーバをDockerで起動したいですか?

docker run --rm --name postgres-quarkus-hibernate -e POSTGRES_USER=quarkus_test \
           -e POSTGRES_PASSWORD=quarkus_test -e POSTGRES_DB=quarkus_test \
           -p 5432:5432 postgres:14.1

これは、永続化されない空のデータベースを起動します。簡単な実験に最適です!

CDI統合

QuarkusでHibernate Reactiveを使用することに慣れている方は、CDIを使用して Mutiny.SessionFactory を注入したことがあると思います。

@Inject
Mutiny.SessionFactory sessionFactory;

これにより、デフォルトの永続化ユニットの Mutiny.SessionFactory が注入されます。

Quarkus 3.0以前は、Mutiny.Session@RequestScoped Beanを注入することも可能でした。しかし、リアクティブセッションのライフサイクルは、CDIリクエストコンテキストのライフサイクルに適合しません。そのため、Quarkus 3.0では、このBeanは削除されました。

テスト

@QuarkusTest で Hibernate Reactive を使用する場合、API の非同期性とすべての操作を Vert.x イベントループで実行する必要から、Hibernate ORM を使用するより少し複雑です。

これらのテストを書くには、2つの要素が必要です。

  • テストメソッドでの @io.quarkus.test.vertx.RunOnVertxContext または @io.quarkus.test.TestReactiveTransaction の使用

  • テストメソッドのパラメータとして io.quarkus.test.vertx.UniAsserter の使用

これらのクラスは、 quarkus-test-vertx の依存関係によって提供されます。

非常にシンプルな使用例は、次のようになります:

@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));
    }

}
アサーション作成に使用できる様々なメソッドの詳細については、 UniAsserter の Javadoc を参照してください。

また、 io.quarkus.test.vertx.UniAsserterInterceptor を拡張して、注入された UniAsserter をラップし、デフォルトの挙動をカスタマイズすることもできます。たとえば、インターセプターを使用して、別のデータベーストランザクション内でアサートメソッドを実行することができます:

@QuarkusTest
public class SomeTest {

   @Test
   @RunOnVertxContext
   public void testEntity(UniAsserter asserter) {
      asserter = new UniAsserterInterceptor(asserter) {
         @Override
         protected <T> Supplier<Uni<T>> transformUni(Supplier<Uni<T>> uniSupplier) {
            return () -> Panache.withTransaction(uniSupplier);
         }
      };
      asserter.execute(() -> new MyEntity().persist());
      asserter.assertEquals(() -> MyEntity.count(), 1l);
      asserter.execute(() -> MyEntity.deleteAll());
   }
}

制限事項など知っておくべきこと

Quarkusは使用しているライブラリを修正しません。このルールはHibernate Reactiveにも適用されます。このエクステンションを使用すると、ほとんどの場合、元のライブラリを使用するのと同じ経験ができます。

しかし、両者は同じコードを共有していますが、Quarkusはいくつかのコンポーネントを自動的に設定し、いくつかの拡張ポイントにカスタム実装を注入しています。

ここでは、QuarkusでHibernate Reactiveを使用する際に注意すべき点を紹介します。

  • Hibernate Reactiveは、 persistence.xml ファイルで設定できません。

  • このエクステンションは、現時点ではデフォルトの永続化ユニットのみを考慮します。 複数の永続化ユニットや、単一の名前付き永続化ユニットを設定することはできません。

  • このエクステンションは、Hibernate ORM と同時に使用することはできません。 https://github.com/quarkusio/quarkus/issues/13425 を参照ください。

  • Enversエクステンションとの統合はサポートされていません。

  • トランザクションの分割は、 jakarta.transaction.Transactional または QuarkusTransaction を使用して行うことはできません。 Hibernate Reactive with Panache を使用する場合は、 代わりに @WithTransaction またはPanache.withTransaction() を使用する ことを検討してください。

PanacheでHibernate Reactiveをシンプルに

Hibernate Reactive with Panacheエクステンションは、Active Recordスタイルのエンティティ(およびリポジトリ)を提供することで、Hibernate Reactiveの使用を促進し、Quarkusでエンティティを簡単に楽しく書けるようにすることに重点を置いています。

関連コンテンツ