REST and Hibernate with Panache

REST
Representational State Transfer

Mid-level Frequently asked 4 min

On this page

The question

What is the difference between the active record and repository patterns in Panache?

30-second answer

Both are Panache patterns over Hibernate ORM (object-relational mapping). In active record, the entity extends PanacheEntity and carries the operations, as static methods such as Order.findById and instance methods such as persist. In the repository pattern, a CDI bean implements PanacheRepository<Order>, and the entity stays a plain JPA (Jakarta Persistence API) class. The operations are the same; the choice is where the code lives and how you test it.

Understand it

Panache: active record or repository?

Compare

Order extends PanacheEntity, so the entity itself carries the queries, such as Order.findById(id) and order.persist(). The code is short, but unit tests need PanacheMock.

View as text

Boxes show what lies between the REST resource and the database, with the call that finds open orders. Four rows compare where queries live, what the entity is, how a unit test mocks it, and how much code it takes.

Active record: Order extends PanacheEntity, so the entity itself carries the queries, such as Order.findById(id) and order.persist(). The code is short, but unit tests need PanacheMock. Queries live in: The entity, as statics. The entity is: A PanacheEntity. Unit test mock: PanacheMock. Code to write: Least.

Repository: OrderRepository implements PanacheRepository<Order>, and the entity stays a plain JPA class. You inject the repository, so a test replaces it with @InjectMock. Queries live in: A repository bean. The entity is: Plain JPA. Unit test mock: @InjectMock. Code to write: One more class.

Boxes show what lies between the REST resource and the database, with the call that finds open orders. Four rows compare where queries live, what the entity is, how a unit test mocks it, and how much code it takes.

Active record: Order extends PanacheEntity, so the entity itself carries the queries, such as Order.findById(id) and order.persist(). The code is short, but unit tests need PanacheMock. Queries live in: The entity, as statics. The entity is: A PanacheEntity. Unit test mock: PanacheMock. Code to write: Least.

Repository: OrderRepository implements PanacheRepository<Order>, and the entity stays a plain JPA class. You inject the repository, so a test replaces it with @InjectMock. Queries live in: A repository bean. The entity is: Plain JPA. Unit test mock: @InjectMock. Code to write: One more class.

Takeaway: Both patterns give the same operations over Hibernate ORM. Active record puts them on the entity; the repository puts them in an injected bean, which is easier to mock.

Two ways to reach Hibernate ORMThe REST resource either calls static methods on an active record entity, or calls an injected repository bean. Both go through Hibernate ORM to the database.OrderResourceActive record:Order.findById(id)Repository:orders.findById(id)Hibernate ORM
Two ways to reach Hibernate ORMThe REST resource either calls static methods on an active record entity, or calls an injected repository bean. Both go through Hibernate ORM to the database.OrderResourceActive record:Order.findById(id)Repository:orders.findById(id)Hibernate ORM
Two ways to reach Hibernate ORM

In code

@Entity
public class Order extends PanacheEntity {
    public String customer;
    public Status status;
    public BigDecimal total;

    public static List<Order> findOpen() {
        return find("status", Status.OPEN).list();
    }
}
Active record: the entity carries its queries
@ApplicationScoped
public class OrderRepository implements PanacheRepository<Order> {

    public List<Order> findOpen(int page) {
        return find("status", Sort.by("id"), Status.OPEN)
                .page(Page.of(page, 20))
                .list();
    }
}
Repository: a bean holds the queries, and the entity stays plain
@Path("/orders")
public class OrderResource {

    @Inject
    OrderRepository orders;

    @GET
    public List<Order> open(@RestQuery @DefaultValue("0") int page) {
        return orders.findOpen(page);
    }

    @POST
    @Transactional
    public RestResponse<Order> create(Order order) {
        orders.persist(order);
        return RestResponse.status(Response.Status.CREATED, order);
    }
}
A REST resource that writes in a transaction
What a POST /orders doesThe request reaches the create method, where the transaction interceptor opens a transaction. The repository persists the order, the transaction commits when the method returns, and the client gets 201 Created.POST /orders@Transactional:a transaction opensorders.persist(order)Commit when themethod returns201 Created
What a POST /orders doesThe request reaches the create method, where the transaction interceptor opens a transaction. The repository persists the order, the transaction commits when the method returns, and the client gets 201 Created.POST /orders@Transactional:a transaction opensorders.persist(order)Commit when themethod returns201 Created
What a POST /orders does

Solve it

The orders endpoint loads the whole table to show 20 rows

GET /orders?status=PAID calls Order.listAll(), filters by status in Java and returns the first 20. With 2 million orders, each call takes seconds and memory spikes. Rewrite it with Panache.

  1. Find the waste. listAll() loads every row and builds an entity per row before Java filters and cuts the list.
  2. Push the filter into SQL. Order.find("status", status) adds a where clause, so only matching rows are read.
  3. Push the page and the sort too. .page(Page.of(index, 20)) adds a limit and an offset; Sort.by("createdAt") adds order by, needed for stable pages.
  4. Return what the client needs. The page of rows plus the total from count(), so the client can draw its pager.
  5. Check. The SQL log shows one limited query and one count, and the response time stays flat as the table grows.
@GET
public OrderPage list(@QueryParam("status") Status status,
                      @QueryParam("page") @DefaultValue("0") int page) {
    PanacheQuery<Order> query = Order.find("status", Sort.by("createdAt").descending(), status)
        .page(Page.of(page, 20));
    return new OrderPage(query.list(), query.count());
}

public record OrderPage(List<Order> items, long total) {}
Filter, sort and page in the database

How to answer

  • PanacheEntity gives a generated Long id; extend PanacheEntityBase to declare your own.
  • Panache entities can use public fields, because Quarkus generates the accessors at build.
  • A repository is mocked with @InjectMock; active record statics need PanacheMock.
  • Writes need @Transactional in both patterns.

Common mistakes

  • Saying active record cannot be unit-tested. PanacheMock replaces its static methods.
  • Thinking Panache replaces Hibernate. It is a layer over Hibernate ORM, which still does the work.

Follow-up questions

How do you write a REST endpoint in Quarkus?

With Jakarta REST annotations, served by Quarkus REST, formerly RESTEasy Reactive. A class with @Path holds methods annotated @GET, @POST and so on. Parameters come from @RestPath, @RestQuery or the body, which Jackson maps. Return the object for 200, or a RestResponse to choose the status. Methods that return Uni or Multi run on the event loop; others run on a worker thread.

  • Resource classes are singletons by default in Quarkus.
  • @ServerExceptionMapper turns an exception into a response.
  • With Hibernate Validator, a failed @Valid parameter returns 400.

See it in the infographic: Panache: active record or repository?

A REST method calls order.persist() and fails with a TransactionRequiredException. Why, and what is the fix?

Hibernate writes only inside a transaction, and Quarkus does not open one for you. Annotate the method that writes, or the service method it calls, with @Transactional from jakarta.transaction. The transaction commits when the method returns and rolls back on a runtime exception. Reads work without one, but group writes that must succeed together in one transaction.

  • Checked exceptions commit unless listed in rollbackOn.
  • ArC also intercepts self-invocation, a call from one method of the bean to another.
  • Panache.withTransaction is the equivalent with Hibernate Reactive.

See it in the infographic: Panache: active record or repository?

How do you query with Panache, and how do you page the results?

Call find with a short form of HQL (Hibernate Query Language): find("status", OPEN) expands to a where clause, and find("status = ?1 and total > ?2", OPEN, 100) takes positional parameters. It returns a PanacheQuery, which you finish with list, firstResult, stream or count. For paging, call page(Page.of(index, size)), and pass a Sort to order the rows.

  • Simple queries can leave out select and from; Panache adds them.
  • list loads every row, so page large tables.
  • For complex queries, write full HQL or project into a smaller class.

See it in the infographic: Panache: active record or repository?

Why can Panache entities use public fields?

Quarkus enhances the entity during the build. It generates a getter and a setter for each public field and rewrites every access to the field, in your code too, into a call to them. You write order.status, Hibernate still goes through accessors, and you can add a custom getter later without changing any caller.

Check yourself

1. A service calls Order.findById(id) on an active record entity. How do you replace that call in a unit test?
Show answers
  • PanacheMock.mock(Order.class): Correct. The quarkus-panache-mock extension can replace static methods of an entity.
  • @InjectMock Order order: Incorrect. An entity is not a CDI (Contexts and Dependency Injection) bean, so there is nothing to inject a mock into.
  • It cannot be replaced: Incorrect. PanacheMock exists for exactly this case.
2. In the repository pattern, where does a custom query such as findOpen live?
Show answers
  • In the repository bean: Correct. The repository implements PanacheRepository and holds the queries for its entity.
  • As a static method on the entity: Incorrect. That is active record. In this pattern the entity stays a plain JPA class.
  • In the REST resource: Incorrect. The resource calls the query. Keeping queries there mixes HTTP and data access.