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

Using Hibernate ORM and Jakarta Persistence

Hibernate ORM is the de facto standard Jakarta Persistence (formerly known as JPA) implementation and offers you the full breadth of an Object Relational Mapper. It works beautifully in Quarkus.

解决方案

我们建议您按照下一节的说明逐步创建应用程序。然而,您可以直接转到已完成的示例。

克隆 Git 仓库: git clone https://github.com/quarkusio/quarkus-quickstarts.git ,或下载一个 存档

The solution is located in the hibernate-orm-quickstart directory.

Setting up and configuring Hibernate ORM

When using Hibernate ORM in Quarkus, you don’t need to have a persistence.xml resource to configure it.

Using such a classic configuration file is an option, but unnecessary unless you have specific advanced needs; so we’ll see first how Hibernate ORM can be configured without a persistence.xml resource.

In Quarkus, you only need to:

  • add your configuration settings in application.properties

  • annotate your entities with @Entity and any other mapping annotation as usual

Other configuration needs have been automated: Quarkus will make some opinionated choices and educated guesses.

Add the following dependencies to your project:

  • the Hibernate ORM extension: io.quarkus:quarkus-hibernate-orm

  • your JDBC driver extension; the following options are available:

比如:

pom.xml
<!-- Hibernate ORM specific dependencies -->
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm</artifactId>
</dependency>

<!-- JDBC driver dependencies -->
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-jdbc-postgresql</artifactId>
</dependency>
build.gradle
// Hibernate ORM specific dependencies
implementation("io.quarkus:quarkus-hibernate-orm")

// JDBC driver dependencies
implementation("io.quarkus:quarkus-jdbc-postgresql")

Annotate your persistent objects with @Entity, then add the relevant configuration properties in application.properties.

Example application.properties
# datasource configuration
quarkus.datasource.db-kind = postgresql
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db

# drop and create the database at startup (use `update` to only update the schema)
quarkus.hibernate-orm.database.generation=drop-and-create

Note that these configuration properties are not the same ones as in your typical Hibernate ORM configuration file. They will often map to Hibernate ORM configuration properties but could have different names and don’t necessarily map 1:1 to each other.

Also, Quarkus will set many Hibernate ORM configuration settings automatically, and will often use more modern defaults.

For a list of the items that you can set in application.properties, see Hibernate ORM configuration properties.

An EntityManagerFactory will be created based on the Quarkus datasource configuration as long as the Hibernate ORM extension is listed among your project dependencies.

The dialect will be selected and configured automatically based on your datasource; you may want to configure it to more precisely match your database.

You can then happily inject your EntityManager:

Example application bean using Hibernate
@ApplicationScoped
public class SantaClausService {
    @Inject
    EntityManager em; (1)

    @Transactional (2)
    public void createGift(String giftDescription) {
        Gift gift = new Gift();
        gift.setName(giftDescription);
        em.persist(gift);
    }
}
1 Inject your entity manager and have fun
2 Mark your CDI bean method as @Transactional and the EntityManager will enlist and flush at commit.
Example 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;
    }
}

To load SQL statements when Hibernate ORM starts, add an import.sql file to the root of your resources directory. This script can contain any SQL DML statements. Make sure to terminate each statement with a semicolon.

This is useful to have a data set ready for your tests or demos.

请确保修改数据库的方法(例如: entity.persist() )处于同一个事务中。给一个CDI bean方法增加 @Transactional 注解,可以确保该方法即事务边界。我们建议在应用端点的边界这样做,比如REST端点的Controller。

Dialect

Supported databases

For supported databases, the Hibernate ORM dialect does not need to be set explicitly: it is selected automatically based on the datasource.

By default, the dialect is configured to target the minimum supported version of the database.

In order for Hibernate ORM to generate more efficient SQL, to avoid workarounds and to take advantage of more database features, you can set the database version explicitly:

application.properties with an explicit db-version
quarkus.datasource.db-kind = postgresql
quarkus.datasource.db-version = 14.0 (1)
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db
1 Set the database version. The Hibernate ORM dialect will target that version.

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.

When a version is set explicitly, Quarkus will try to check this version against the actual database version on startup, leading to a startup failure when the actual version is lower.

This is because Hibernate ORM may generate SQL that is invalid for versions of the database older than what is configured, which would lead to runtime exceptions.

If the database cannot be reached, a warning will be logged but startup will proceed.

Other databases

If your database does not have a corresponding Quarkus extension, or if the defaults do not match your needs for some reason, you will need to set the Hibernate ORM dialect explicitly:

application.properties with an explicit dialect
quarkus.datasource.db-kind = postgresql
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:26257/hibernate_db

quarkus.hibernate-orm.dialect=org.hibernate.dialect.CockroachDialect (1)
1 Set the Hibernate ORM dialect.

In that case, keep in mind that the JDBC driver or Hibernate ORM dialect may not work properly in GraalVM native executables.

As with supported databases, you can configure the DB version explicitly to get the most out of Hibernate ORM:

application.properties with an explicit dialect and db-version
quarkus.datasource.db-kind = postgresql
quarkus.datasource.db-version = 22.2 (1)
quarkus.datasource.username = hibernate
quarkus.datasource.password = hibernate
quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:26257/hibernate_db

quarkus.hibernate-orm.dialect=org.hibernate.dialect.CockroachDialect (2)
1 Set the database version. The Hibernate ORM dialect will target that version. Since we’re targeting CockroachDB here, we’re passing the CockroachDB version, not the PostgreSQL version.
2 Set the Hibernate ORM dialect.

Hibernate ORM configuration properties

There are various optional properties useful to refine your EntityManagerFactory or guide guesses of Quarkus.

There are no required properties, as long as a default datasource is configured.

When no property is set, Quarkus can typically infer everything it needs to set up Hibernate ORM and will have it use the default datasource.

The configuration properties listed here allow you to override such defaults, and customize and tune various aspects.

Configuration property fixed at build time - All other configuration properties are overridable at runtime

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

long

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

long

About the Duration format

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

You can also use a simplified format, starting with a number:

  • If the value is only a number, it represents time in seconds.

  • If the value is a number followed by ms, it represents time in milliseconds.

In other cases, the simplified format is translated to the java.time.Duration format for parsing:

  • If the value is a number followed by h, m, or s, it is prefixed with PT.

  • If the value is a number followed by d, it is prefixed with P.

Do not mix persistence.xml and quarkus.hibernate-orm.* properties in application.properties. Quarkus will raise an exception. Make up your mind on which approach you want to use.

If your classpath contains a persistence.xml that you want to ignore, set the following configuration property:

quarkus.hibernate-orm.persistence-xml.ignore=true

Want to start a PostgreSQL server on the side with Docker?

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

This will start a non-durable empty database: ideal for a quick experiment!

Multiple persistence units

Setting up multiple persistence units

It is possible to define multiple persistence units using the Quarkus configuration properties.

The properties at the root of the quarkus.hibernate-orm. namespace define the default persistence unit. For instance, the following snippet defines a default datasource and a default persistence unit:

quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:default;DB_CLOSE_DELAY=-1

quarkus.hibernate-orm.database.generation=drop-and-create

Using a map based approach, it is possible to define named persistence units:

quarkus.datasource."users".db-kind=h2 (1)
quarkus.datasource."users".jdbc.url=jdbc:h2:mem:users;DB_CLOSE_DELAY=-1

quarkus.datasource."inventory".db-kind=h2 (2)
quarkus.datasource."inventory".jdbc.url=jdbc:h2:mem:inventory;DB_CLOSE_DELAY=-1

quarkus.hibernate-orm."users".database.generation=drop-and-create (3)
quarkus.hibernate-orm."users".datasource=users (4)
quarkus.hibernate-orm."users".packages=org.acme.model.user (5)

quarkus.hibernate-orm."inventory".database.generation=drop-and-create (6)
quarkus.hibernate-orm."inventory".datasource=inventory
quarkus.hibernate-orm."inventory".packages=org.acme.model.inventory
1 Define a datasource named users.
2 Define a datasource named inventory.
3 Define a persistence unit called users.
4 Define the datasource used by the persistence unit.
5 This configuration property is important, but we will discuss it a bit later.
6 Define a persistence unit called inventory pointing to the inventory datasource.

You can mix the default datasource and named datasources or only have one or the other.

The default persistence unit points to the default datasource by default. For named persistence units, the datasource property is mandatory. You can point your persistence unit to the default datasource by setting it to <default> (which is the internal name of the default datasource).

It is perfectly valid to have several persistence units pointing to the same datasource.

Attaching model classes to persistence units

There are two ways to attach model classes to persistence units, and they should not be mixed:

  • Via the packages configuration property;

  • Via the @io.quarkus.hibernate.orm.PersistenceUnit package-level annotation.

If both are mixed, the annotations are ignored and only the packages configuration properties are taken into account.

Using the packages configuration property is simple:

quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.hibernate-orm.packages=org.acme.model.defaultpu

quarkus.hibernate-orm."users".database.generation=drop-and-create
quarkus.hibernate-orm."users".datasource=users
quarkus.hibernate-orm."users".packages=org.acme.model.user

This configuration snippet will create two persistence units:

  • The default one which will contain all the model classes under the org.acme.model.defaultpu package, subpackages included.

  • A named users persistence unit which will contain all the model classes under the org.acme.model.user package, subpackages included.

You can attach several packages to a persistence unit:

quarkus.hibernate-orm."users".packages=org.acme.model.shared,org.acme.model.user

All the model classes under the org.acme.model.shared and org.acme.model.user packages will be attached to the users persistence unit.

It is also supported to attach a given model class to several persistence units.

Model classes need to be consistently added to a given persistence unit. That meant that all dependent model classes of a given entity (mapped super classes, embeddables…​) are required to be attached to the persistence unit. As we are dealing with the persistence unit at the package level, it should be simple enough.

Panache entities can be attached to only one persistence unit.

For entities attached to several persistence units, you cannot use Panache. You can mix the two approaches though and mix Panache entities and traditional entities where multiple persistence units are required.

If you have a use case for that and clever ideas about how to implement it without cluttering the simplified Panache approach, contact us on the quarkus-dev mailing list.

The second approach to attach model classes to a persistence unit is to use package-level @io.quarkus.hibernate.orm.PersistenceUnit annotations. Again, the two approaches cannot be mixed.

To obtain a configuration similar to the one above with the packages configuration property, create a package-info.java file with the following content:

@PersistenceUnit("users") (1)
package org.acme.model.user;

import io.quarkus.hibernate.orm.PersistenceUnit;
1 Be careful, use the @io.quarkus.hibernate.orm.PersistenceUnit annotation, not the Jakarta Persistence one.

We only support defining the @PersistenceUnit for model classes at the package level, using the @PersistenceUnit annotation at the class level is not supported in this case.

Note that, similarly to what we do with the configuration property, we take into account the annotated package but also all its subpackages.

CDI integration

If you are familiar with using Hibernate ORM in Quarkus, you probably already have injected the EntityManager using CDI:

@Inject
EntityManager entityManager;

This will inject the EntityManager of the default persistence unit.

Injecting the EntityManager of a named persistence unit (users in our example) is as simple as:

@Inject
@PersistenceUnit("users") (1)
EntityManager entityManager;
1 Here again, we use the same @io.quarkus.hibernate.orm.PersistenceUnit annotation.

You can inject the EntityManagerFactory of a named persistence unit using the exact same mechanism:

@Inject
@PersistenceUnit("users")
EntityManagerFactory entityManagerFactory;

Activate/deactivate persistence units

If a persistence unit is configured at build time, by default it is active at runtime, that is Quarkus will start the corresponding Hibernate ORM SessionFactory on application startup.

To deactivate a persistence unit at runtime, set quarkus.hibernate-orm[.optional name].active to false. Then Quarkus will not start the corresponding Hibernate ORM SessionFactory on application startup. Any attempt to use the corresponding persistence unit at runtime will fail with a clear error message.

This is in particular useful when you want an application to be able to use one of a pre-determined set of datasources at runtime.

For example, with the following configuration:

quarkus.hibernate-orm."pg".packages=org.acme.model.shared
quarkus.hibernate-orm."pg".datasource=pg
quarkus.hibernate-orm."pg".database.generation=drop-and-create
quarkus.hibernate-orm."pg".active=false
quarkus.datasource."pg".db-kind=h2
quarkus.datasource."pg".active=false
quarkus.datasource."pg".jdbc.url=jdbc:postgresql:///your_database

quarkus.hibernate-orm."oracle".packages=org.acme.model.shared
quarkus.hibernate-orm."oracle".datasource=oracle
quarkus.hibernate-orm."oracle".database.generation=drop-and-create
quarkus.hibernate-orm."oracle".active=false
quarkus.datasource."oracle".db-kind=oracle
quarkus.datasource."oracle".active=false
quarkus.datasource."oracle".jdbc.url=jdbc:oracle:///your_database

Setting quarkus.hibernate-orm."pg".active=true and quarkus.datasource."pg".active=true at runtime will make only the PostgreSQL persistence unit and datasource available, and setting quarkus.hibernate-orm."oracle".active=true and quarkus.datasource."oracle".active=true at runtime will make only the Oracle persistence unit and datasource available.

Custom configuration profiles can help simplify such a setup. By appending the following profile-specific configuration to the one above, you can select a persistence unit/datasource at runtime simply by setting quarkus.profile: quarkus.profile=prod,pg or quarkus.profile=prod,oracle.

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

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

It can also be useful to define a CDI bean producer redirecting to the currently active persistence unit, like this:

public class MyProducer {
    @Inject
    DataSourceSupport dataSourceSupport;

    @Inject
    @PersistenceUnit("pg")
    Session pgSessionBean;

    @Inject
    @PersistenceUnit("oracle")
    Session oracleSessionBean;

    @Produces
    @ApplicationScoped
    public Session session() {
        if (dataSourceSupport.getInactiveNames().contains("pg")) {
            return oracleSessionBean;
        } else {
            return pgSessionBean;
        }
    }
}

Setting up and configuring Hibernate ORM with a persistence.xml

Alternatively, you can use a META-INF/persistence.xml to set up Hibernate ORM. This is useful for:

  • migrating existing code

  • when you have relatively complex settings requiring the full flexibility of the configuration

  • or if you like it the good old way

If you use a persistence.xml, then you cannot use the quarkus.hibernate-orm.* properties and only persistence units defined in persistence.xml will be taken into account.

If your classpath contains a persistence.xml that you want to ignore, set the following configuration property:

quarkus.hibernate-orm.persistence-xml.ignore=true

Your pom.xml dependencies as well as your Java code would be identical to the precedent example. The only difference is that you would specify your Hibernate ORM configuration in META-INF/persistence.xml:

Example persistence.xml resource
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="CustomerPU" transaction-type="JTA">

        <description>My customer entities</description>

        <properties>
            <!-- Connection specific -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>

            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>

            <!--
                Optimistically create the tables;
                will cause background errors being logged if they already exist,
                but is practical to retain existing data across runs (or create as needed) -->
            <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create"/>

            <property name="jakarta.persistence.validation.mode" value="NONE"/>
        </properties>

    </persistence-unit>
</persistence>

When using the persistence.xml configuration you are configuring Hibernate ORM directly, so in this case the appropriate reference is the documentation on hibernate.org.

Please remember these are not the same property names as the ones used in the Quarkus application.properties, nor will the same defaults be applied.

XML mapping

Hibernate ORM in Quarkus supports XML mapping. You can add mapping files following the orm.xml format (Jakarta Persistence) or the hbm.xml format (specific to Hibernate ORM, deprecated):

XML mapping files are parsed at build time.

The file META-INF/orm.xml will always be included by default, if it exists in the classpath.

If that is not what you want, use quarkus.hibernate-orm.mapping-files = no-file or <mapping-file>no-file</mapping-file>.

在外部项目或jar中定义实体

Hibernate ORM in Quarkus relies on compile-time bytecode enhancements to your entities. If you define your entities in the same project where you build your Quarkus application, everything will work fine.

If the entities come from external projects or jars, you can make sure that your jar is treated like a Quarkus application library by adding an empty META-INF/beans.xml file.

This will allow Quarkus to index and enhance your entities as if they were inside the current project.

Hibernate ORM in development mode

Quarkus development mode is really useful for applications that mix front end or services and database access.

There are a few common approaches to make the best of it.

The first choice is to use quarkus.hibernate-orm.database.generation=drop-and-create in conjunction with import.sql.

That way for every change to your app and in particular to your entities, the database schema will be properly recreated and your data fixture (stored in import.sql) will be used to repopulate it from scratch. This is best to perfectly control your environment and works magic with Quarkus live reload mode: your entity changes or any change to your import.sql is immediately picked up and the schema updated without restarting the application!

By default, in dev and test modes, Hibernate ORM, upon boot, will read and execute the SQL statements in the /import.sql file (if present). You can change the file name by changing the property quarkus.hibernate-orm.sql-load-script in application.properties.

The second approach is to use quarkus.hibernate-orm.database.generation=update. This approach is best when you do many entity changes but still need to work on a copy of the production data or if you want to reproduce a bug that is based on specific database entries. update is a best effort from Hibernate ORM and will fail in specific situations including altering your database structure which could lead to data loss. For example if you change structures which violate a foreign key constraint, Hibernate ORM might have to bail out. But for development, these limitations are acceptable.

The third approach is to use quarkus.hibernate-orm.database.generation=none. This approach is best when you are working on a copy of the production data but want to fully control the schema evolution. Or if you use a database schema migration tool like Flyway or Liquibase.

With this approach when making changes to an entity, make sure to adapt the database schema accordingly; you could also use validate to have Hibernate verify the schema matches its expectations.

Do not use quarkus.hibernate-orm.database.generation drop-and-create and update in your production environment.

These approaches become really powerful when combined with Quarkus configuration profiles. You can define different configuration profiles to select different behaviors depending on your environment. This is great because you can define different combinations of Hibernate ORM properties matching the development style you currently need.

application.properties
%dev.quarkus.hibernate-orm.database.generation = drop-and-create
%dev.quarkus.hibernate-orm.sql-load-script = import-dev.sql

%dev-with-data.quarkus.hibernate-orm.database.generation = update
%dev-with-data.quarkus.hibernate-orm.sql-load-script = no-file

%prod.quarkus.hibernate-orm.database.generation = none
%prod.quarkus.hibernate-orm.sql-load-script = no-file

You can start dev mode using a custom profile:

CLI
quarkus dev -Dquarkus.profile=dev-with-data
Maven
./mvnw quarkus:dev -Dquarkus.profile=dev-with-data
Gradle
./gradlew --console=plain quarkusDev -Dquarkus.profile=dev-with-data

Hibernate ORM in production mode

Quarkus comes with default profiles (dev, test and prod). And you can add your own custom profiles to describe various environments (staging, prod-us, etc).

The Hibernate ORM Quarkus extension sets some default configurations differently in dev and test modes than in other environments.

  • quarkus.hibernate-orm.sql-load-script is set to no-file for all profiles except the dev and test ones.

You can override it in your application.properties explicitly (e.g. %prod.quarkus.hibernate-orm.sql-load-script = import.sql) but we wanted you to avoid overriding your database by accident in prod :)

Speaking of, make sure to not drop your database schema in production! Add the following in your properties file.

application.properties
%prod.quarkus.hibernate-orm.database.generation = none
%prod.quarkus.hibernate-orm.sql-load-script = no-file

Automatically transitioning to Flyway to Manage Schemas

If you have the Flyway extension installed when running in development mode, Quarkus provides a simple way to turn your Hibernate ORM auto generated schema into a Flyway migration file. This is intended to make is easy to move from the early development phase, where Hibernate can be used to quickly set up the schema, to the production phase, where Flyway is used to manage schema changes.

To use this feature simply open the Dev UI when the quarkus-flyway extension is installed and click in the Datasources link in the Flyway pane. Hit the Create Initial Migration button and the following will happen:

  • A db/migration/V1.0.0__{appname}.sql file will be created, containing the SQL Hibernate is running to generate the schema

  • quarkus.flyway.baseline-on-migrate will be set, telling Flyway to automatically create its baseline tables

  • quarkus.flyway.migrate-at-start will be set, telling Flyway to automatically apply migrations on application startup

  • %dev.quarkus.flyway.clean-at-start and %test.quarkus.flyway.clean-at-start will be set, to clean the DB after reload in dev/test mode

This button is simply a convenience to quickly get you started with Flyway, it is up to you to determine how you want to manage your database schemas in production. In particular the migrate-at-start setting may not be right for all environments.

Caching

Applications that frequently read the same entities can see their performance improved when the Hibernate ORM second-level cache is enabled.

Caching of entities

To enable second-level cache, mark the entities that you want cached with @jakarta.persistence.Cacheable:

@Entity
@Cacheable
public class Country {
    int dialInCode;
    // ...
}

When an entity is annotated with @Cacheable, all its field values are cached except for collections and relations to other entities.

This means the entity can be loaded without querying the database, but be careful as it implies the loaded entity might not reflect recent changes in the database.

Caching of collections and relations

Collections and relations need to be individually annotated to be cached; in this case the Hibernate specific @org.hibernate.annotations.Cache should be used, which requires also to specify the CacheConcurrencyStrategy:

package org.acme;

@Entity
@Cacheable
public class Country {
    // ...

    @OneToMany
    @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
    List<City> cities;

    // ...
}

Caching of queries

Queries can also benefit from second-level caching. Cached query results can be returned immediately to the caller, avoiding to run the query on the database.

Be careful as this implies the results might not reflect recent changes.

To cache a query, mark it as cacheable on the Query instance:

Query query = ...
query.setHint("org.hibernate.cacheable", Boolean.TRUE);

If you have a NamedQuery then you can enable caching directly on its definition, which will usually be on an entity:

@Entity
@NamedQuery(name = "Fruits.findAll",
      query = "SELECT f FROM Fruit f ORDER BY f.name",
      hints = @QueryHint(name = "org.hibernate.cacheable", value = "true") )
public class Fruit {
   ...

That’s all! Caching technology is already integrated and enabled by default in Quarkus, so it’s enough to set which ones are safe to be cached.

Tuning of Cache Regions

Caches store the data in separate regions to isolate different portions of data; such regions are assigned a name, which is useful for configuring each region independently, or to monitor their statistics.

By default, entities are cached in regions named after their fully qualified name, e.g. org.acme.Country.

Collections are cached in regions named after the fully qualified name of their owner entity and collection field name, separated by # character, e.g. org.acme.Country#cities.

All cached queries are by default kept in a single region dedicated to them called default-query-results-region.

All regions are bounded by size and time by default. The defaults are 10000 max entries, and 100 seconds as maximum idle time.

The size of each region can be customized via the quarkus.hibernate-orm.cache."<region_name>".memory.object-count property (Replace <region_name> with the actual region name).

To set the maximum idle time, provide the duration (see note on duration’s format below) via the quarkus.hibernate-orm.cache."<region_name>".expiration.max-idle property (Replace <region_name> with the actual region name).

The double quotes are mandatory if your region name contains a dot. For instance:

quarkus.hibernate-orm.cache."org.acme.MyEntity".memory.object-count=1000

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

You can also use a simplified format, starting with a number:

  • If the value is only a number, it represents time in seconds.

  • If the value is a number followed by ms, it represents time in milliseconds.

In other cases, the simplified format is translated to the java.time.Duration format for parsing:

  • If the value is a number followed by h, m, or s, it is prefixed with PT.

  • If the value is a number followed by d, it is prefixed with P.

Limitations of Caching

The caching technology provided within Quarkus is currently quite rudimentary and limited.

The team thought it was better to have some caching capability to start with, than having nothing; you can expect better caching solution to be integrated in future releases, and any help and feedback in this area is very welcome.

These caches are kept locally, so they are not invalidated or updated when changes are made to the persistent store by other applications.

Also, when running multiple copies of the same application (in a cluster, for example on Kubernetes/OpenShift), caches in separate copies of the application aren’t synchronized.

For these reasons, enabling caching is only suitable when certain assumptions can be made: we strongly recommend that only entities, collections and queries which never change are cached. Or at most, that when indeed such an entity is mutated and allowed to be read out of date (stale) this has no impact on the expectations of the application.

Following this advice guarantees applications get the best performance out of the second-level cache and yet avoid unexpected behaviour.

On top of immutable data, in certain contexts it might be acceptable to enable caching also on mutable data; this could be a necessary tradeoff on selected entities which are read frequently and for which some degree of staleness is acceptable; this " acceptable degree of staleness" can be tuned by setting eviction properties. This is however not recommended and should be done with extreme care, as it might produce unexpected and unforeseen effects on the data.

Rather than enabling caching on mutable data, ideally a better solution would be to use a clustered cache; however at this time Quarkus doesn’t provide any such implementation: feel free to get in touch and let this need known so that the team can take this into account.

Finally, the second-level cache can be disabled globally by setting hibernate.cache.use_second_level_cache to false; this is a setting that needs to be specified in the persistence.xml configuration file.

When second-level cache is disabled, all cache annotations are ignored and all queries are run ignoring caches; this is generally useful only to diagnose issues.

Hibernate Envers

The Envers extension to Hibernate ORM aims to provide an easy auditing / versioning solution for entity classes.

In Quarkus, Envers has a dedicated Quarkus Extension io.quarkus:quarkus-hibernate-envers; you just need to add this to your project to start using it.

Additional dependency to enable Hibernate Envers
    <!-- Add the Hibernate Envers extension -->
    <dependency>
        <groupId>io.quarkus</groupId>
        <artifactId>quarkus-hibernate-envers</artifactId>
    </dependency>

At this point the extension does not expose additional configuration properties.

For more information about Hibernate Envers, see hibernate.org/orm/envers/.

指标

Either Micrometer or SmallRye Metrics are capable of exposing metrics that Hibernate ORM collects at runtime. To enable exposure of Hibernate metrics on the /q/metrics endpoint, make sure your project depends on a metrics extension and set the configuration property quarkus.hibernate-orm.metrics.enabled to true. When using SmallRye Metrics, metrics will be available under the vendor scope.

Limitations and other things you should know

Quarkus does not modify the libraries it uses; this rule applies to Hibernate ORM as well: when using this extension you will mostly have the same experience as using the original library.

But while they share the same code, Quarkus does configure some components automatically and injects custom implementations for some extension points; this should be transparent and useful but if you’re an expert of Hibernate you might want to know what is being done.

Automatic build time enhancement

Hibernate ORM can use build time enhanced entities; normally this is not mandatory, but it’s useful and will have your applications perform better.

Typically, you would need to adapt your build scripts to include the Hibernate Enhancement plugins; in Quarkus this is not necessary as the enhancement step is integrated in the build and analysis of the Quarkus application.

Due to the usage of enhancement, using the clone() method on entities is currently not supported as it will also clone some enhancement-specific fields that are specific to the entity.

This limitation might be removed in the future.

Automatic integration

Transaction Manager integration

You don’t need to set this up, Quarkus automatically injects the reference to the Narayana Transaction Manager. The dependency is included automatically as a transitive dependency of the Hibernate ORM extension. All configuration is optional; for more details see Using Transactions in Quarkus.

Connection pool

Don’t need to choose one either. Quarkus automatically includes the Agroal connection pool; configure your datasource as in the above examples and it will set up Hibernate ORM to use Agroal. More details about this connection pool can be found in Quarkus - Datasources.

Second Level Cache

As explained earlier in the Caching section, you don’t need to pick an implementation. A suitable implementation based on technologies from Infinispan and Caffeine is included as a transitive dependency of the Hibernate ORM extension, and automatically integrated during the build.

Limitations

XML mapping with duplicate files in the classpath

XML mapping files are expected to have a unique path.

In practice, it’s only possible to have duplicate XML mapping files in the classpath in very specific scenarios. For example, if two JARs include a META-INF/orm.xml file (with the exact same path but in different JARs), then the mapping file path META-INF/orm.xml can only be referenced from a persistence.xml in the same JAR as the META-INF/orm.xml file.

JMX

Management beans are not working in GraalVM native images; therefore, Hibernate’s capability to register statistics and management operations with the JMX bean is disabled when compiling into a native image. This limitation is likely permanent, as it’s not a goal for native images to implement support for JMX. All such metrics can be accessed in other ways.

JACC Integration

Hibernate ORM’s capability to integrate with JACC is disabled when building GraalVM native images, as JACC is not available - nor useful - in native mode.

Binding the Session to ThreadLocal context

It is impossible to use the ThreadLocalSessionContext helper of Hibernate ORM as support for it is not implemented. Since Quarkus provides out-of-the-box CDI support, injection or programmatic CDI lookup is a better approach. This feature also didn’t integrate well with reactive components and more modern context propagation techniques, making us believe this legacy feature has no future. If you badly need to bind it to a ThreadLocal, it should be trivial to implement in your own code.

JNDI

The JNDI technology is commonly used in other runtimes to integrate different components. A common use case is Java Enterprise servers to bind the TransactionManager and the Datasource components to a name and then have Hibernate ORM configured to look these components up by name. But in Quarkus, this use case doesn’t apply as components are injected directly, making JNDI support an unnecessary legacy. To avoid unexpected use of JNDI, full support for JNDI has been disabled in the Hibernate ORM extension for Quarkus. This is both a security precaution and an optimization.

Other notable differences

Format of import.sql

When importing a import.sql to set up your database, keep in mind that Quarkus reconfigures Hibernate ORM so to require a semicolon (;) to terminate each statement. The default in Hibernate is to have a statement per line, without requiring a terminator other than newline: remember to convert your scripts to use the ; terminator character if you’re reusing existing scripts. This is useful so to allow multi-line statements and human friendly formatting.

Simplifying Hibernate ORM with Panache

The Hibernate ORM with Panache extension facilitates the usage of Hibernate ORM by providing active record style entities (and repositories) and focuses on making your entities trivial and fun to write in Quarkus.

Configure your datasource

Datasource configuration is extremely simple, but is covered in a different guide as technically it’s implemented by the Agroal connection pool extension for Quarkus.

Jump over to Quarkus - Datasources for all details.

Multitenancy

"The term multitenancy, in general, is applied to software development to indicate an architecture in which a single running instance of an application simultaneously serves multiple clients (tenants). This is highly common in SaaS solutions. Isolating information (data, customizations, etc.) pertaining to the various tenants is a particular challenge in these systems. This includes the data owned by each tenant stored in the database" (Hibernate User Guide).

Quarkus currently supports the separate database approach, the separate schema approach and the discriminator approach.

To see multitenancy in action, you can check out the hibernate-orm-multi-tenancy-quickstart quickstart.

编写应用程序

Let’s start by implementing the /{tenant} endpoint. As you can see from the source code below it is just a regular Jakarta REST resource:

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

@ApplicationScoped
@Path("/{tenant}")
public class FruitResource {

    @Inject
    EntityManager entityManager;

    @GET
    @Path("fruits")
    public Fruit[] getFruits() {
        return entityManager.createNamedQuery("Fruits.findAll", Fruit.class)
                .getResultList().toArray(new Fruit[0]);
    }

}

In order to resolve the tenant from incoming requests and map it to a specific tenant configuration, you need to create an implementation for the io.quarkus.hibernate.orm.runtime.tenant.TenantResolver interface.

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.hibernate.orm.runtime.tenant.TenantResolver;
import io.vertx.ext.web.RoutingContext;

@PersistenceUnitExtension (1)
@RequestScoped (2)
public class CustomTenantResolver implements TenantResolver {

    @Inject
    RoutingContext context;

    @Override
    public String getDefaultTenantId() {
        return "base";
    }

    @Override
    public String resolveTenantId() {
        String path = context.request().path();
        String[] parts = path.split("/");

        if (parts.length == 0) {
            // resolve to default tenant config
            return getDefaultTenantId();
        }

        return parts[1];
    }

}
1 Annotate the TenantResolver implementation with the @PersistenceUnitExtension qualifier to tell Quarkus it should be used in the default persistence unit.

For named persistence units, use @PersistenceUnitExtension("nameOfYourPU").

2 The bean is made @RequestScoped as the tenant resolution depends on the incoming request.

From the implementation above, tenants are resolved from the request path so that in case no tenant could be inferred, the default tenant identifier is returned.

If you also use OIDC multitenancy and both OIDC and Hibernate ORM tenant IDs are the same and must be extracted from the Vert.x RoutingContext then you can pass the tenant id from the OIDC Tenant Resolver to the Hibernate ORM Tenant Resolver as a RoutingContext attribute, for example:

import io.quarkus.hibernate.orm.runtime.tenant.TenantResolver;
import io.vertx.ext.web.RoutingContext;

@PersistenceUnitExtension
@RequestScoped
public class CustomTenantResolver implements TenantResolver {

    @Inject
    RoutingContext context;
    ...
    @Override
    public String resolveTenantId() {
        // OIDC TenantResolver has already calculated the tenant id and saved it as a RoutingContext `tenantId` attribute:
        return context.get("tenantId");
    }
}

配置该应用程序

In general, it is not possible to use the Hibernate ORM database generation feature in conjunction with a multitenancy setup. Therefore, you have to disable it, and you need to make sure that the tables are created per schema. The following setup will use the Flyway extension to achieve this goal.

SCHEMA approach

The same data source will be used for all tenants and a schema has to be created for every tenant inside that data source. CAUTION: Some databases like MariaDB/MySQL do not support database schemas. In these cases you have to use the DATABASE approach below.

# Disable generation
quarkus.hibernate-orm.database.generation=none

# Enable SCHEMA approach and use default datasource
quarkus.hibernate-orm.multitenant=SCHEMA
# You could use a non-default datasource by using the following setting
# quarkus.hibernate-orm.multitenant-schema-datasource=other

# The default data source used for all tenant schemas
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=quarkus_test
quarkus.datasource.password=quarkus_test
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/quarkus_test

# Enable Flyway configuration to create schemas
quarkus.flyway.schemas=base,mycompany
quarkus.flyway.locations=classpath:schema
quarkus.flyway.migrate-at-start=true

Here is an example of the Flyway SQL (V1.0.0__create_fruits.sql) to be created in the configured folder src/main/resources/schema.

CREATE SEQUENCE base.known_fruits_id_seq;
SELECT setval('base."known_fruits_id_seq"', 3);
CREATE TABLE base.known_fruits
(
  id   INT,
  name VARCHAR(40)
);
INSERT INTO base.known_fruits(id, name) VALUES (1, 'Cherry');
INSERT INTO base.known_fruits(id, name) VALUES (2, 'Apple');
INSERT INTO base.known_fruits(id, name) VALUES (3, 'Banana');

CREATE SEQUENCE mycompany.known_fruits_id_seq;
SELECT setval('mycompany."known_fruits_id_seq"', 3);
CREATE TABLE mycompany.known_fruits
(
  id   INT,
  name VARCHAR(40)
);
INSERT INTO mycompany.known_fruits(id, name) VALUES (1, 'Avocado');
INSERT INTO mycompany.known_fruits(id, name) VALUES (2, 'Apricots');
INSERT INTO mycompany.known_fruits(id, name) VALUES (3, 'Blackberries');

DATABASE approach

For every tenant you need to create a named data source with the same identifier that is returned by the TenantResolver.

# Disable generation
quarkus.hibernate-orm.database.generation=none

# Enable DATABASE approach
quarkus.hibernate-orm.multitenant=DATABASE

# Default tenant 'base'
quarkus.datasource.base.db-kind=postgresql
quarkus.datasource.base.username=quarkus_test
quarkus.datasource.base.password=quarkus_test
quarkus.datasource.base.jdbc.url=jdbc:postgresql://localhost:5432/quarkus_test

# Tenant 'mycompany'
quarkus.datasource.mycompany.db-kind=postgresql
quarkus.datasource.mycompany.username=mycompany
quarkus.datasource.mycompany.password=mycompany
quarkus.datasource.mycompany.jdbc.url=jdbc:postgresql://localhost:5433/mycompany

# Flyway configuration for the default datasource
quarkus.flyway.locations=classpath:database/default
quarkus.flyway.migrate-at-start=true

# Flyway configuration for the mycompany datasource
quarkus.flyway.mycompany.locations=classpath:database/mycompany
quarkus.flyway.mycompany.migrate-at-start=true

Following are examples of the Flyway SQL files to be created in the configured folder src/main/resources/database.

Default schema (src/main/resources/database/default/V1.0.0__create_fruits.sql):

CREATE SEQUENCE known_fruits_id_seq;
SELECT setval('known_fruits_id_seq', 3);
CREATE TABLE known_fruits
(
  id   INT,
  name VARCHAR(40)
);
INSERT INTO known_fruits(id, name) VALUES (1, 'Cherry');
INSERT INTO known_fruits(id, name) VALUES (2, 'Apple');
INSERT INTO known_fruits(id, name) VALUES (3, 'Banana');

Mycompany schema (src/main/resources/database/mycompany/V1.0.0__create_fruits.sql):

CREATE SEQUENCE known_fruits_id_seq;
SELECT setval('known_fruits_id_seq', 3);
CREATE TABLE known_fruits
(
  id   INT,
  name VARCHAR(40)
);
INSERT INTO known_fruits(id, name) VALUES (1, 'Avocado');
INSERT INTO known_fruits(id, name) VALUES (2, 'Apricots');
INSERT INTO known_fruits(id, name) VALUES (3, 'Blackberries');

DISCRIMINATOR approach

The default data source will be used for all tenants. All entities defining a field annotated with @TenantId will have that field populated automatically, and will get filtered automatically in queries.

# Enable DISCRIMINATOR approach
quarkus.hibernate-orm.multitenant=DISCRIMINATOR

# The default data source used for all tenant schemas
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=quarkus_test
quarkus.datasource.password=quarkus_test
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/quarkus_test

Programmatically Resolving Tenants Connections

If you need a more dynamic configuration for the different tenants you want to support and don’t want to end up with multiple entries in your configuration file, you can use the io.quarkus.hibernate.orm.runtime.tenant.TenantConnectionResolver interface to implement your own logic for retrieving a connection. Creating an application-scoped bean that implements this interface and annotating it with @PersistenceUnitExtension (or @PersistenceUnitExtension("nameOfYourPU") for a named persistence unit) will replace the current Quarkus default implementation io.quarkus.hibernate.orm.runtime.tenant.DataSourceTenantConnectionResolver. Your custom connection resolver would allow for example to read tenant information from a database and create a connection per tenant at runtime based on it.

Interceptors

You can assign an org.hibernate.Interceptor to your SessionFactory by simply defining a CDI bean with the appropriate qualifier:

@PersistenceUnitExtension (1)
public static class MyInterceptor extends EmptyInterceptor { (2)
    @Override
    public boolean onLoad(Object entity, Serializable id, Object[] state, (3)
            String[] propertyNames, Type[] types) {
        // ...
        return false;
    }
}
1 Annotate the interceptor implementation with the @PersistenceUnitExtension qualifier to tell Quarkus it should be used in the default persistence unit.

For named persistence units, use @PersistenceUnitExtension("nameOfYourPU")

2 Either extend org.hibernate.EmptyInterceptor or implement org.hibernate.Interceptor directly.
3 Implement methods as necessary.

By default, interceptor beans annotated with @PersistenceUnitExtension are application-scoped, which means only one interceptor instance will be created per application and reused across all entity managers. For this reason, the interceptor implementation must be thread-safe.

In order to create one interceptor instance per entity manager instead, annotate your bean with @Dependent. In that case, the interceptor implementation doesn’t need to be thread-safe.

Due to a limitation in Hibernate ORM itself, @PreDestroy methods on @Dependent-scoped interceptors will never get called.

Statement Inspectors

You can assign a org.hibernate.engine.jdbc.spi.StatementInspector to your SessionFactory by simply defining a CDI bean with the appropriate qualifier:

@PersistenceUnitExtension (1)
public class MyStatementInspector implements StatementInspector { (2)
    @Override
    public String inspect(String sql) {
        // ...
        return sql;
    }
}
1 Annotate the statement inspector implementation with the @PersistenceUnitExtension qualifier to tell Quarkus it should be used in the default persistence unit.

For named persistence units, use @PersistenceUnitExtension("nameOfYourPU")

2 Implement org.hibernate.engine.jdbc.spi.StatementInspector.

Customizing JSON/XML serialization/deserialization

By default, Quarkus will try to automatically configure format mappers depending on available extensions. Globally configured ObjectMapper (or Jsonb) will be used for serialization/deserialization operations when Jackson (or JSON-B) is available. Jackson will take precedence if both Jackson and JSON-B are available at the same time.

JSON and XML serialization/deserialization in Hibernate ORM can be customized by implementing a org.hibernate.type.format.FormatMapper and annotating the implementation with the appropriate qualifiers:

@JsonFormat (1)
@PersistenceUnitExtension (2)
public class MyJsonFormatMapper implements FormatMapper { (3)
    @Override
    public <T> T fromString(CharSequence charSequence, JavaType<T> javaType, WrapperOptions wrapperOptions) {
        // ...
    }

    @Override
    public <T> String toString(T value, JavaType<T> javaType, WrapperOptions wrapperOptions) {
       // ...
    }
}
1 Annotate the format mapper implementation with the @JsonFormat qualifier to tell Quarkus that this mapper is specific to JSON serialization/deserialization.
2 Annotate the format mapper implementation with the @PersistenceUnitExtension qualifier to tell Quarkus it should be used in the default persistence unit.

For named persistence units, use @PersistenceUnitExtension("nameOfYourPU")

3 Implement org.hibernate.type.format.FormatMapper.

In case of a custom XML format mapper, a different CDI qualifier must be applied:

@XmlFormat (1)
@PersistenceUnitExtension (2)
public class MyJsonFormatMapper implements FormatMapper { (3)
    @Override
    public <T> T fromString(CharSequence charSequence, JavaType<T> javaType, WrapperOptions wrapperOptions) {
        // ...
    }

    @Override
    public <T> String toString(T value, JavaType<T> javaType, WrapperOptions wrapperOptions) {
       // ...
    }
}
1 Annotate the format mapper implementation with the @XmlFormat qualifier to tell Quarkus that this mapper is specific to XML serialization/deserialization.
2 Annotate the format mapper implementation with the @PersistenceUnitExtension qualifier to tell Quarkus it should be used in the default persistence unit.

For named persistence units, use @PersistenceUnitExtension("nameOfYourPU")

3 Implement org.hibernate.type.format.FormatMapper.

Format mappers must have both @PersistenceUnitExtension and either @JsonFormat or @XmlFormat CDI qualifiers applied.

Having multiple JSON (or XML) format mappers registered for the same persistence unit will result in an exception, because of the ambiguity.

Related content