Quarkus - Using Hibernate ORM and JPA

Hibernate ORM is the de facto standard JPA implementation and offers you the full breadth of an Object Relational Mapper. It works beautifully in Quarkus.

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

Example dependencies using Maven

  1. <dependencies>
  2. <!-- Hibernate ORM specific dependencies -->
  3. <dependency>
  4. <groupId>io.quarkus</groupId>
  5. <artifactId>quarkus-hibernate-orm</artifactId>
  6. </dependency>
  7. <!-- JDBC driver dependencies -->
  8. <dependency>
  9. <groupId>io.quarkus</groupId>
  10. <artifactId>quarkus-jdbc-postgresql</artifactId>
  11. </dependency>
  12. </dependencies>

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

Example application.properties

  1. # datasource configuration
  2. quarkus.datasource.db-kind = postgresql
  3. quarkus.datasource.username = hibernate
  4. quarkus.datasource.password = hibernate
  5. quarkus.datasource.jdbc.url = jdbc:postgresql://localhost:5432/hibernate_db
  6. # drop and create the database at startup (use `update` to only update the schema)
  7. 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: these drive Quarkus configuration properties, which often will map to Hibernate configuration properties but could have different names and don’t necessarily map 1:1 to each other.

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

Please see below section Hibernate ORM configuration properties for the list of properties you can set in application.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 based on the JDBC driver - unless you set one explicitly.

You can then happily inject your EntityManager:

Example application bean using Hibernate

  1. @ApplicationScoped
  2. public class SantaClausService {
  3. @Inject
  4. EntityManager em; (1)
  5. @Transactional (2)
  6. public void createGift(String giftDescription) {
  7. Gift gift = new Gift();
  8. gift.setName(giftDescription);
  9. em.persist(gift);
  10. }
  11. }
1Inject your entity manager and have fun
2Mark your CDI bean method as @Transactional and the EntityManager will enlist and flush at commit.

Example Entity

  1. @Entity
  2. public class Gift {
  3. private Long id;
  4. private String name;
  5. @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="giftSeq")
  6. public Long getId() {
  7. return id;
  8. }
  9. public void setId(Long id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. }

To load some SQL statements when Hibernate ORM starts, add an import.sql in the root of your resources directory. Such a 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.

Make sure to wrap methods modifying your database (e.g. entity.persist()) within a transaction. Marking a CDI bean method @Transactional will do that for you and make that method a transaction boundary. We recommend doing so at your application entry point boundaries like your REST endpoint controllers.

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 setup 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.

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.

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.

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

  1. docker run ulimit memlock=-1:-1 -it rm=true memory-swappiness=0 \
  2. name postgres-quarkus-hibernate -e POSTGRES_USER=hibernate \
  3. -e POSTGRES_PASSWORD=hibernate -e POSTGRES_DB=hibernate_db \
  4. -p 5432:5432 postgres:10.5

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

Setting up and configuring Hibernate ORM with a persistence.xml

Alternatively, you can use a META-INF/persistence.xml to setup 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 have 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.

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

  1. <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
  4. http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
  5. version="2.1">
  6. <persistence-unit name="CustomerPU" transaction-type="JTA">
  7. <description>My customer entities</description>
  8. <properties>
  9. <!-- Connection specific -->
  10. <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL95Dialect"/>
  11. <property name="hibernate.show_sql" value="true"/>
  12. <property name="hibernate.format_sql" value="true"/>
  13. <!--
  14. Optimistically create the tables;
  15. will cause background errors being logged if they already exist,
  16. but is practical to retain existing data across runs (or create as needed) -->
  17. <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
  18. <property name="javax.persistence.validation.mode" value="NONE"/>
  19. </properties>
  20. </persistence-unit>
  21. </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.

Defining entities in external projects or jars

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.

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

  1. %dev.quarkus.hibernate-orm.database.generation = drop-and-create
  2. %dev.quarkus.hibernate-orm.sql-load-script = import-dev.sql
  3. %dev-with-data.quarkus.hibernate-orm.database.generation = update
  4. %dev-with-data.quarkus.hibernate-orm.sql-load-script = no-file
  5. %prod.quarkus.hibernate-orm.database.generation = none
  6. %prod.quarkus.hibernate-orm.sql-load-script = no-file

Start “dev mode” using a custom profile via Maven

  1. ./mvnw compile quarkus:dev -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

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

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 @javax.persistence.Cacheable:

  1. @Entity
  2. @Cacheable
  3. public class Country {
  4. int dialInCode;
  5. // ...
  6. }

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:

  1. package org.acme;
  2. @Entity
  3. @Cacheable
  4. public class Country {
  5. // ...
  6. @OneToMany
  7. @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
  8. List<City> cities;
  9. // ...
  10. }

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:

  1. Query query = ...
  2. 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:

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

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:

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

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.

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

  1. <!-- Add the Hibernate Envers extension -->
  2. <dependency>
  3. <groupId>io.quarkus</groupId>
  4. <artifactId>quarkus-hibernate-envers</artifactId>
  5. </dependency>

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

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

Metrics

The SmallRye Metrics extension is capable of exposing metrics that Hibernate ORM collects at runtime. To enable exposure of Hibernate metrics on the /metrics endpoint, make sure your project depends on the quarkus-smallrye-metrics artifact and set the configuration property quarkus.hibernate-orm.metrics.enabled to true. Metrics will then 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.

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; just configure your datasource as in the above examples and it will setup Hibernate ORM to use Agroal. More details about this connection pool can be found in Quarkus - Datasources.

Second Level Cache

as explained above in section Caching, 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

Hibernate ORM allows to map entities using XML files; this capability isn’t enabled in Quarkus: use annotations instead as Quarkus can handle them very efficiently. This limitation could be lifted in the future, if there’s a compelling need for it and if someone contributes it.

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

Essentially using the ThreadLocalSessionContext helper of Hibernate ORM is not implemented. The team believes this isn’t a big deal as it’s trivial to inject the Session via CDI instead, or handling the binding into a ThreadLocal yourself, making this a legacy feature. This limitation might be resolved in the future, if someone opens a ticket for it and provides a reasonable use case to justify the need.

JPA Callbacks

Annotations allowing for application callbacks on entity lifecycle events defined by JPA such as @javax.persistence.PostUpdate, @javax.persistence.PostLoad, @javax.persistence.PostPersist, etc…​ are currently not processed. This limitation could be resolved in a future version, depending on user demand.

Single instance

It is currently not possible to configure more than one instance of Hibernate ORM. This is a temporary limitation, the team is working on it - please be patient!

Other notable differences

Format of import.sql

When importing a import.sql to setup 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 and the separate schema approach.

Writing the application

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

  1. import javax.enterprise.context.ApplicationScoped;
  2. import javax.inject.Inject;
  3. import javax.persistence.EntityManager;
  4. import javax.ws.rs.Consumes;
  5. import javax.ws.rs.GET;
  6. import javax.ws.rs.Path;
  7. import javax.ws.rs.Produces;
  8. @ApplicationScoped
  9. @Produces("application/json")
  10. @Consumes("application/json")
  11. @Path("/{tenant}")
  12. public class FruitResource {
  13. @Inject
  14. EntityManager entityManager;
  15. @GET
  16. @Path("fruits")
  17. public Fruit[] getFruits() {
  18. return entityManager.createNamedQuery("Fruits.findAll", Fruit.class)
  19. .getResultList().toArray(new Fruit[0]);
  20. }
  21. }

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.

  1. import javax.enterprise.context.ApplicationScoped;
  2. import io.quarkus.arc.Arc;
  3. import io.quarkus.arc.Unremovable;
  4. import io.quarkus.hibernate.orm.runtime.tenant.TenantResolver;
  5. import io.vertx.ext.web.RoutingContext;
  6. @RequestScoped
  7. @Unremovable
  8. public class CustomTenantResolver implements TenantResolver {
  9. @Inject
  10. RoutingContext context;
  11. @Override
  12. public String getDefaultTenantId() {
  13. return "base";
  14. }
  15. @Override
  16. public String resolveTenantId() {
  17. String path = context.request().path();
  18. String[] parts = path.split("/");
  19. if (parts.length == 0) {
  20. // resolve to default tenant config
  21. return getDefaultTenantId();
  22. }
  23. return parts[1];
  24. }
  25. }

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.

Configuring the application

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.

  1. # Disable generation
  2. quarkus.hibernate-orm.database.generation=none
  3. # Enable SCHEMA approach and use default datasource
  4. quarkus.hibernate-orm.multitenant=SCHEMA
  5. # You could use a non-default datasource by using the following setting
  6. # quarkus.hibernate-orm.multitenant-schema-datasource=other
  7. # The default data source used for all tenant schemas
  8. quarkus.datasource.db-kind=postgresql
  9. quarkus.datasource.username=quarkus_test
  10. quarkus.datasource.password=quarkus_test
  11. quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/quarkus_test
  12. # Enable Flyway configuration to create schemas
  13. quarkus.flyway.schemas=base,mycompany
  14. quarkus.flyway.locations=classpath:schema
  15. 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.

  1. CREATE SEQUENCE base.known_fruits_id_seq;
  2. SELECT setval('base."known_fruits_id_seq"', 3);
  3. CREATE TABLE base.known_fruits
  4. (
  5. id INT,
  6. name VARCHAR(40)
  7. );
  8. INSERT INTO base.known_fruits(id, name) VALUES (1, 'Cherry');
  9. INSERT INTO base.known_fruits(id, name) VALUES (2, 'Apple');
  10. INSERT INTO base.known_fruits(id, name) VALUES (3, 'Banana');
  11. CREATE SEQUENCE mycompany.known_fruits_id_seq;
  12. SELECT setval('mycompany."known_fruits_id_seq"', 3);
  13. CREATE TABLE mycompany.known_fruits
  14. (
  15. id INT,
  16. name VARCHAR(40)
  17. );
  18. INSERT INTO mycompany.known_fruits(id, name) VALUES (1, 'Avocado');
  19. INSERT INTO mycompany.known_fruits(id, name) VALUES (2, 'Apricots');
  20. 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.

  1. # Disable generation
  2. quarkus.hibernate-orm.database.generation=none
  3. # Enable DATABASE approach
  4. quarkus.hibernate-orm.multitenant=DATABASE
  5. # Default tenant 'base'
  6. quarkus.datasource.base.db-kind=postgresql
  7. quarkus.datasource.base.username=quarkus_test
  8. quarkus.datasource.base.password=quarkus_test
  9. quarkus.datasource.base.jdbc.url=jdbc:postgresql://localhost:5432/quarkus_test
  10. # Tenant 'mycompany'
  11. quarkus.datasource.mycompany.db-kind=postgresql
  12. quarkus.datasource.mycompany.username=mycompany
  13. quarkus.datasource.mycompany.password=mycompany
  14. quarkus.datasource.mycompany.jdbc.url=jdbc:postgresql://localhost:5433/mycompany
  15. # Flyway configuration for the default datasource
  16. quarkus.flyway.locations=classpath:database/default
  17. quarkus.flyway.migrate-at-start=true
  18. # Flyway configuration for the mycompany datasource
  19. quarkus.flyway.mycompany.locations=classpath:database/mycompany
  20. 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):

  1. CREATE SEQUENCE known_fruits_id_seq;
  2. SELECT setval('known_fruits_id_seq', 3);
  3. CREATE TABLE known_fruits
  4. (
  5. id INT,
  6. name VARCHAR(40)
  7. );
  8. INSERT INTO known_fruits(id, name) VALUES (1, 'Cherry');
  9. INSERT INTO known_fruits(id, name) VALUES (2, 'Apple');
  10. INSERT INTO known_fruits(id, name) VALUES (3, 'Banana');

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

  1. CREATE SEQUENCE known_fruits_id_seq;
  2. SELECT setval('known_fruits_id_seq', 3);
  3. CREATE TABLE known_fruits
  4. (
  5. id INT,
  6. name VARCHAR(40)
  7. );
  8. INSERT INTO known_fruits(id, name) VALUES (1, 'Avocado');
  9. INSERT INTO known_fruits(id, name) VALUES (2, 'Apricots');
  10. INSERT INTO known_fruits(id, name) VALUES (3, 'Blackberries');

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 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.