Skip to content
javahacks.dev
Quarkus

Quarkus Hibernate Reactive With Mutiny and Panache Basics

Use Hibernate Reactive in Quarkus with Mutiny: the Uni and Multi return types, reactive Panache, transactions and when blocking ORM is the better choice.

6 min read
Summarize in AI
Flat illustration of startup time of a JVM compared with a native image, with the Quarkus, Hibernate, OpenJDK and Kubernetes logos.

A reactive stack does not hold a thread while it waits on the database. Hibernate Reactive brings the familiar ORM mapping to that model, and in Quarkus 3 it comes with Panache, so the entity code looks much like the blocking version. What changes is everything about how a result reaches the caller. This guide builds a small product service with Mutiny, then spends as long on the rules and on the question of whether to use it at all, because on JDK 25 the answer is less obvious than it was.

Dependencies and configuration

XML
<dependency><groupId>io.quarkus</groupId><artifactId>quarkus-hibernate-reactive-panache</artifactId></dependency>
<dependency><groupId>io.quarkus</groupId><artifactId>quarkus-reactive-pg-client</artifactId></dependency>
properties
quarkus.datasource.db-kind=postgresql
%prod.quarkus.datasource.reactive.url=postgresql://db:5432/shop

There is no JDBC datasource here. The reactive client speaks the PostgreSQL wire protocol directly over non-blocking sockets, so a JDBC driver on the classpath is not used by this stack. In dev mode and in tests, Dev Services still starts a PostgreSQL container and wires the URL for you, so the %prod line is the only connection setting you write. Migrations still need JDBC: Flyway runs through its own blocking datasource at startup, which is fine because it happens before the service takes traffic.

The entity

java
@Entity
public class Product extends PanacheEntity {

    public String name;
    public BigDecimal price;

    public static Uni<List<Product>> cheaperThan(BigDecimal limit) {
        return list("price < ?1", limit);
    }
}

The entity looks like blocking Panache. The static finder returns Uni<List<Product>>, which is a promise of a list that is computed when something subscribes to it. Nothing runs when you call cheaperThan; the query is sent when the framework subscribes to the returned Uni, which is why you return it from a resource method instead of storing it.

The resource

java
@Path("/products")
public class ProductResource {

    @GET
    public Uni<List<Product>> list() {
        return Product.listAll();
    }

    @POST
    @WithTransaction
    public Uni<Response> create(Product product) {
        return product.<Product>persist()
                .map(saved -> Response.status(201).entity(saved).build());
    }

    @GET
    @Path("/{id}")
    public Uni<Product> get(@PathParam("id") Long id) {
        return Product.<Product>findById(id)
                .onItem().ifNull().failWith(() -> new NotFoundException());
    }
}

@WithTransaction opens a reactive session and a transaction around the returned Uni and commits when it completes. A read-only method uses @WithSession where no session is open already. Both differ from @Transactional, which does not apply to reactive code, and mixing them up is the first error most people hit. The ifNull().failWith line turns a missing row into a 404; without it the endpoint returns an empty 200.

Rules of the model

Blocking is forbidden on the event loop. Calling .await().indefinitely() on a Uni, or a JDBC call, from an event loop thread makes Quarkus throw a BlockingOperationNotAllowedException, and the exception is the framework protecting the loop, which serves many requests on a few threads. Work that must block moves to a worker thread with @Blocking.

Compose, do not nest. Chain steps with map, flatMap and chain, and return the final Uni. Subscribing inside a callback detaches the inner work from the transaction and from error handling, and the bug shows up as data that is saved only sometimes.

A reactive session is bound to the pipeline and is not thread safe. Do not stash an entity loaded in one pipeline and use it in another, and do not share a session between concurrent branches.

Lazy loading needs an explicit fetch. An association is loaded with Mutiny.fetch(entity.items), not by calling the getter. Touching it without fetching gives the reactive equivalent of LazyInitializationException, and the stack trace points at the getter, not at the missing fetch.

Should you use it

Reactive code improves memory and thread use when a service waits on many slow calls at the same time. The price is a different programming model, a smaller ecosystem of reactive drivers and harder debugging, since stack traces cross asynchronous boundaries. And virtual threads, final since JDK 21, change the comparison: a blocking Hibernate ORM service can handle thousands of concurrent requests with plain imperative code, because a blocked virtual thread costs little. If the motive is only scale, try that first. Choose Hibernate Reactive when the surrounding code is already reactive, for example a pipeline built on Mutiny streams or Kafka reactive messaging, and measure with your own workload; the sizing arithmetic is in thread pool sizing.

Testing a reactive resource

Test with @QuarkusTest and REST Assured as usual, because the HTTP surface is the same. For code that returns a Uni directly, use UniAssertSubscriber, or call .await().atMost(Duration.ofSeconds(5)) in the test thread, which is safe there because the test thread is not an event loop. Vert.x provides @RunOnVertxContext for tests that need the event loop. Write at least one test that fails a query and checks the error path, since reactive errors travel as failures on the Uni and an unhandled one is easy to lose.

Streaming a large result

A Uni<List<Product>> loads the whole result into memory before the response starts. For a large table, return a Multi<Product> so rows flow to the client as they arrive.

java
@GET
@Path("/export")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Multi<Product> export() {
    return Product.streamAll();
}

streamAll needs an open session for the duration of the stream, so annotate the method with @WithSession, or wrap the stream with Panache.withSession. The benefit is bounded memory, and the cost is that an error in the middle of a response arrives after the status line is sent, so clients must handle a truncated stream. Apply back-pressure by letting the client's consumption rate drive the demand, which Mutiny does without extra code when the transport supports it.

Error handling and timeouts

Failures travel on the Uni, so handle them there. onFailure().recoverWithItem(...) supplies a fallback, onFailure(PersistenceException.class).transform(...) maps a database error to a domain exception, and ifNoItem().after(Duration.ofSeconds(2)).fail() puts a bound on a slow query. Without a timeout, a request that waits on a stuck connection holds its resources until the client gives up. Set the pool size and the connection acquisition timeout in configuration too, because a reactive client multiplexes requests over a small pool, and an undersized one shows up as latency spikes rather than errors.

Metrics for the reactive stack

Add Micrometer and watch the connection pool and the event loop, not only request counts. A rising number of pending acquisitions means the pool is too small for the load. Long event loop pauses mean something blocked, and the extension can log a warning when a handler runs too long. Alert on those two signals, because they appear before users notice slow responses.

Where Hibernate Reactive falls short

Not every Hibernate ORM feature is available, and dialect support lags the blocking stack in places. Mixing blocking and reactive ORM in one application is possible with separate persistence units, and it is rarely wise. The reference is the Hibernate Reactive with Panache guide, and the Mutiny documentation explains Uni and Multi.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.