Skip to content
javahacks.dev
Quarkus

Quarkus Hibernate ORM Panache Active Record and Repository

Use Hibernate ORM with Panache in Quarkus: active record and repository styles, queries, paging and transactions, with Dev Services as the database.

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

Panache is the Quarkus layer that removes the boilerplate around Hibernate ORM. The mapping rules are the same as in the Hibernate guide. This is for Quarkus 3.

Setup

XML
<dependency><groupId>io.quarkus</groupId><artifactId>quarkus-hibernate-orm-panache</artifactId></dependency>
<dependency><groupId>io.quarkus</groupId><artifactId>quarkus-jdbc-postgresql</artifactId></dependency>
properties
quarkus.datasource.db-kind=postgresql
%dev.quarkus.hibernate-orm.schema-management.strategy=drop-and-create

With no quarkus.datasource.jdbc.url in dev and test, Dev Services starts PostgreSQL in a container. In production set the URL and credentials from the environment, as in configuration profiles.

Active record

java
@Entity
public class Customer extends PanacheEntity {     // adds a Long id
    public String name;
    public String email;
    public boolean active;

    public static List<Customer> activeByName(String name) {
        return list("active = true and lower(name) like ?1", "%" + name.toLowerCase() + "%");
    }
}

Fields are public, and Panache generates accessors at build time. The entity gets persist(), delete(), findById, listAll, count and find. Use it like this:

java
@POST
@Transactional
public Response create(Customer customer) {
    customer.persist();
    return Response.status(201).entity(customer).build();
}

@GET
public List<Customer> search(@QueryParam("name") String name) {
    return Customer.activeByName(name);
}

Repository style

java
@ApplicationScoped
public class CustomerRepository implements PanacheRepository<Customer> {
    public List<Customer> inactive() { return list("active", false); }
}

The entity is a plain class with @Entity, and the repository injects like any bean. This style suits teams that want entities free of persistence logic, and it is the one closest to Spring Data. The trade is the same as in the repository pattern post.

Queries and paging

java
PanacheQuery<Customer> query = Customer.find("active", Sort.by("name"), true);
List<Customer> page = query.page(Page.of(0, 20)).list();
long total = query.count();

A query starting with a bare condition is expanded to from Customer where .... Named parameters work with Parameters.with("name", n). Projections use .project(CustomerSummary.class) with a record.

Transactions

@Transactional from jakarta.transaction starts a JTA transaction, and Quarkus does not open one for a REST method by default. A write without it fails with TransactionRequiredException, which in Spring terms is the same error. Keep the annotation on the service or resource method that owns the unit of work.

Testing

java
@QuarkusTest
class CustomerTest {
    @Test @TestTransaction
    void persistsAndFinds() {
        Customer c = new Customer(); c.name = "Ada"; c.persist();
        assertEquals(1, Customer.count("name", "Ada"));
    }
}

@TestTransaction rolls the test back. The container starts once per test run.

Choosing a style

Active record is quick for CRUD-heavy services and reads well in small codebases, because the finder sits next to the fields it queries. The repository style costs one more class per entity and pays back when entities are shared between modules, when you want to mock the data access in unit tests, or when the team already thinks in Spring Data terms. Either way the entity stays a normal Hibernate entity, so you can switch styles one entity at a time without changing the schema.

Projections and avoiding the entity

Panache queries return entities by default, and loading a whole entity to show two columns is wasteful. Use a projection to a record:

java
public record OrderSummary(Long id, String status) {}

List<OrderSummary> list = Order.find("status", "NEW")
        .project(OrderSummary.class).list();

Panache generates a select of only those columns, using the record's constructor parameter names, so keep them equal to the entity field names. For read-heavy screens this halves the data moved and avoids lazy-loading surprises, because a record has nothing to lazy-load.

Pagination and the count trap

page(Page.of(0, 20)) limits the query, and pageCount() runs a separate count query. Call it only when you need the total, since on a large table the count costs as much as scanning it. Always add a Sort or an order by, because a paged query without an ordering returns rows in whatever order the database likes, and two consecutive pages can overlap or skip rows.

Transactions and the reactive variant

Mutating calls need an active transaction, and the usual way is @Transactional on the method of an @ApplicationScoped bean. A persist() outside a transaction fails with TransactionRequiredException. A common mistake is to annotate a private method or to call the annotated method from inside the same class, and both skip the interceptor. The reactive flavor, Hibernate Reactive with Panache, uses @WithTransaction and returns Uni, and mixing it with blocking calls on the event loop stalls the application, so choose one model per service and stay with it.

Testing

For a repository-style design, mock the repository in a unit test, and test queries against a real database through Dev Services, which starts a container on its own for the test profile. The quarkus-panache-mock module lets you mock static methods of an active record entity, which works but is a sign: a static method is hard to replace, and that is the argument for the repository style when the logic around the queries grows.

Panache and the N plus 1 problem

Panache is a thin layer over Hibernate, and it inherits every Hibernate behavior, including lazy loading. A list of orders that renders each order's customer name issues one query for the orders and one more per order unless you fetch the association together. Panache queries accept a join fetch in the HQL string, such as Order.find("from Order o join fetch o.customer where o.status = ?1", "NEW"), and that removes the extra queries for that screen. Turn on SQL logging in the dev profile with quarkus.hibernate-orm.log.sql=true and read the statements while you click through a page, because the count of queries is the number that tells you whether the mapping is right, and no code review will find it as fast.

Choosing between active record and repository, once more

The active record style puts queries on the entity as static methods, which is short and pleasant for a small service with simple rules. The repository style puts them on a separate class that you inject, which costs one more file per entity and pays back in tests and in layering. Our rule is to start with the repository when the entity has more than a handful of queries or any business logic around them, and to use active record for lookup tables and simple CRUD. Both styles can live in the same project, and nothing stops you from moving an entity from one to the other, since the query strings are the same.

Schema management and test data

During development quarkus.hibernate-orm.database.generation=drop-and-create builds the schema from the entities, and an import.sql file loads sample rows at startup. Neither belongs in production. For anything that ships, use Flyway or Liquibase migrations and set generation to none or validate, so the application checks that the entities match the schema and refuses to start when they do not. A mismatch found at startup costs a failed deploy, while one found at run time costs a failed request in front of a customer.

Where this does not apply

Panache hides less than it seems, so lazy loading and flush rules still apply, including N plus 1. For non-blocking code use the reactive flavour in Hibernate Reactive. The reference is the Panache guide, and Hibernate ORM in Quarkus covers configuration.

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