jabrena/plinth / skills/412-frameworks-quarkus-panache
412-frameworks-quarkus-panache
VerifiedUse when you need data access with Quarkus Hibernate ORM Panache — including PanacheEntity / PanacheEntityBase, PanacheRepository, named queries, JPQL, native SQL, DTO projections (project(Class)), pagination (Page.of()), N+1 avoidance (JOIN FETCH), optimistic locking (@Version / OptimisticLockException), @NamedQuery for validated reusable queries, transactions, @TestTransaction for test isolation, and immutable-friendly patterns. This is the Quarkus analogue to Spring Data for relational persistence. This should trigger for requests such as Review Panache entities or repositories in Quarkus; Improve Hibernate ORM data access with Panache; Add DTO projections, JOIN FETCH, pagination, or optimistic locking to Panache queries; Fix N+1 query problems or add @Version concurrency control in Quarkus Panache; Improve Panache active record versus repository design. Part of Plinth Toolkit
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.6 KB |
| references/412-frameworks-quarkus-panache.md | markdown | 22.8 KB |
references/412-frameworks-quarkus-panache.md
View on GitHub---
name: 412-frameworks-quarkus-panache
description: Use when you need data access with Quarkus Hibernate ORM Panache — including PanacheEntity / PanacheEntityBase, PanacheRepository, named queries, JPQL, native SQL, transactions, pagination, and immutable-friendly patterns. This is the Quarkus analogue to Spring Data for relational persistence; prefer Panache APIs over verbose persistence boilerplate. For Flyway-backed DDL and versioned schema changes, use `@413-frameworks-quarkus-db-migrations-flyway`.
license: Apache-2.0
metadata:
author: Juan Antonio Breña Moral
version: 0.19.0
---
# Hibernate ORM with Panache
## Role
You are a Senior software engineer with extensive experience in Quarkus, Hibernate ORM, and Panache
## Goal
Panache simplifies Hibernate ORM in Quarkus: **active record** (`PanacheEntity`) for small entities or **repository** (`PanacheRepository`) for a cleaner separation. Prefer explicit queries (`find`, `list`, JPQL) over magic lazy graphs; keep aggregates focused; use `@Transactional` on services. Use native queries when you want SQL you control and still stay in Hibernate (transactions, same datasource, optional entity mapping). For hand-written SQL and reporting that should bypass Hibernate at the application boundary, use `@411-frameworks-quarkus-jdbc` instead of forcing everything through Panache. For schema evolution with Flyway, use `@413-frameworks-quarkus-db-migrations-flyway`.
## Constraints
Before applying any recommendations, ensure the project is in a valid state by running Maven compilation. Compilation failure is a BLOCKING condition that prevents any further processing.
- **MANDATORY**: Run `./mvnw compile` or `mvn compile` before applying any change
- **PREREQUISITE**: Project must compile successfully before persistence changes
- **CRITICAL SAFETY**: If compilation fails, IMMEDIATELY STOP and DO NOT CONTINUE
- **VERIFY**: Run `./mvnw clean verify` or `mvn clean verify` after applying improvements
- **BLOCKING CONDITION**: Compilation errors must be resolved by the user before proceeding with persistence changes
- **NO EXCEPTIONS**: Under no circumstances should Panache recommendations be applied to a project that fails to compile
## Examples
### Table of contents
- Example 1: Active record entity
- Example 2: Panache repository
- Example 3: Service layer transaction
- Example 4: Parameterized JPQL queries
- Example 5: DTO projections
- Example 6: Pagination
- Example 7: @NamedQuery for stable, reused queries
- Example 8: JOIN FETCH to avoid N+1 queries
- Example 9: @Version for optimistic locking
- Example 10: Testing with @QuarkusTest and @TestTransaction
### Example 1: Active record entity
Title: extends PanacheEntity
Description: `PanacheEntity` provides `id` and helpers such as `findById`, `listAll`, `persist`. Keep entities focused; avoid embedding HTTP concerns.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.Column;
@Entity
public class Book extends PanacheEntity {
@Column(nullable = false)
public String title;
public boolean published;
public static Book findByTitle(String title) {
return find("title", title).firstResult();
}
}
```
**Bad example:**
```java
// Bad: entity knows about JAX-RS Response
@Entity
public class Book extends PanacheEntity {
public jakarta.ws.rs.core.Response asJson() {
return jakarta.ws.rs.core.Response.ok(this).build();
}
}
```
### Example 2: Panache repository
Title: implements PanacheRepository
Description: Repositories keep persistence off the entity type and fit layered architectures.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
public List<Book> publishedBy(String author) {
return list("author = ?1 and published = ?2", author, true);
}
}
```
**Bad example:**
```java
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
public List<Book> search(String userFragment) {
return list("FROM Book WHERE title LIKE '" + userFragment + "%'");
// injection risk — never concatenate user input into JPQL
}
}
```
### Example 3: Service layer transaction
Title: @Transactional around use cases
Description: Coordinate multiple repository calls inside one `@Transactional` service method.
**Good example:**
```java
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
@ApplicationScoped
public class CatalogService {
private final BookRepository books;
@Inject
public CatalogService(BookRepository books) {
this.books = books;
}
@Transactional
public void publish(long bookId) {
Book b = books.findById(bookId);
if (b == null) {
throw new NotFoundException();
}
b.published = true;
}
}
```
**Bad example:**
```java
// Bad: REST resource opens transaction per call without cohesive service
@PUT
public void publish(@PathParam("id") long id) {
Book b = Book.findById(id);
b.published = true;
// scattered transaction boundaries — harder to test and reuse
}
```
### Example 4: Parameterized JPQL queries
Title: Positional and named parameters; firstResultOptional for single rows
Description: Panache offers three levels of query syntax: field shorthand for simple equality, positional `?1` parameters, and full JPQL with `Parameters.with(...)` for named bindings. Use `firstResultOptional()` for single-row lookups rather than `findById` when querying by non-PK columns. Never concatenate user input into query strings.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Parameters;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
import java.util.Optional;
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
// Shorthand: single field equality
public List<Book> findPublished() {
return find("published", true).list();
}
// Positional parameters: readable for 2–3 bindings
public List<Book> findByAuthorAndGenre(String author, String genre) {
return find("author = ?1 AND genre = ?2 ORDER BY title", author, genre).list();
}
// Named parameters: preferred for long or reused queries
public Optional<Book> findMostRecentByAuthor(String author) {
return find("author = :author ORDER BY publishedAt DESC",
Parameters.with("author", author))
.firstResultOptional();
}
}
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
public List<Book> searchByAuthor(String fragment) {
// Bad: query injection risk — never build query strings from user input
return find("FROM Book WHERE author LIKE '%" + fragment + "%'").list();
}
}
```
### Example 5: DTO projections
Title: project(Class) for column-selective reads; manual mapping for computed fields
Description: Use `project(Class)` to fetch only the columns a DTO interface or record needs, reducing data transfer and avoiding accidental exposure of internal entity fields in API responses. When computed columns or joins are required, use manual stream mapping to a record DTO instead.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Parameters;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
// Lightweight DTO — only the fields the API caller needs
public interface BookSummary {
String getTitle();
String getAuthor();
}
// Record DTO for computed or manually mapped projections
record BookCard(String title, String author, boolean published) {}
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
// project(Class): Panache selects only projected columns
public List<BookSummary> listSummaries() {
return find("published = true ORDER BY title")
.project(BookSummary.class)
.list();
}
// Manual mapping when the DTO has computed fields or custom logic
public List<BookCard> listCards(String author) {
return find("author = :author ORDER BY title",
Parameters.with("author", author))
.stream()
.map(b -> new BookCard(b.title, b.author, b.published))
.toList();
}
}
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.Entity;
import jakarta.persistence.Column;
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import java.util.List;
@Entity
public class Book extends PanacheEntity {
public String title;
public String author;
public boolean published;
@Column(name = "internal_cost")
public java.math.BigDecimal internalCost; // sensitive — should never reach the API
}
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
// Bad: returning managed entities leaks internal fields (internalCost) to callers
public List<Book> listPublished() {
return find("published", true).list();
}
}
```
### Example 6: Pagination
Title: page(Page.of(index, size)) for bounded lists; expose count and page count to callers
Description: Unbounded `listAll()` or `list(query)` calls will load the entire table into memory. Use `page(Page.of(pageIndex, pageSize))` to fetch one page at a time. Expose `query.count()` and `query.pageCount()` so callers can build navigation controls.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Page;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
record PagedResult<T>(List<T> items, long totalCount, int pageCount) {}
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
public PagedResult<Book> listPublished(int pageIndex, int pageSize) {
PanacheQuery<Book> query = find("published = true ORDER BY title");
query.page(Page.of(pageIndex, pageSize));
return new PagedResult<>(
query.list(),
query.count(),
query.pageCount()
);
}
}
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
// Bad: listAll() loads the entire books table — OOM risk on large datasets
public List<Book> listPublished() {
return listAll();
}
}
```
### Example 7: @NamedQuery for stable, reused queries
Title: Declare on the entity; invoke with # prefix; validated at startup
Description: `@NamedQuery` declarations are parsed and validated by Hibernate at application startup, catching query parse errors early. Use them for frequently executed, stable queries to enable Hibernate's query plan caching and to centralise SQL intent near the entity it queries.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import io.quarkus.panache.common.Parameters;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.Entity;
import jakarta.persistence.NamedQuery;
import java.util.List;
@Entity
@NamedQuery(
name = "Book.findPublishedByGenre",
query = "FROM Book WHERE genre = :genre AND published = true ORDER BY title"
)
public class Book extends PanacheEntity {
public String title;
public String author;
public String genre;
public boolean published;
}
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
public List<Book> findPublishedByGenre(String genre) {
// # prefix invokes the named query — validated at startup
return find("#Book.findPublishedByGenre",
Parameters.with("genre", genre))
.list();
}
}
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> {
// Bad: inline JPQL string is validated at runtime only —
// a typo in "plblished" is not caught until the query is first executed
public List<Book> findPublishedByGenre(String genre) {
return find("FROM Book WHERE genre = ?1 AND plblished = true ORDER BY title", genre).list();
}
}
```
### Example 8: JOIN FETCH to avoid N+1 queries
Title: Eagerly load associations in one JPQL query instead of triggering lazy loads per entity
Description: When a use case iterates a collection association on every returned entity, issuing N individual `SELECT` statements. Use `JOIN FETCH` in JPQL to load the association in the same query. Outside of an open Hibernate session (e.g. serializing to JSON), lazy access throws `LazyInitializationException`.
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.OneToMany;
import java.util.List;
@Entity
public class Order extends PanacheEntity {
public long customerId;
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
public List<OrderItem> items;
}
@Entity
public class OrderItem extends PanacheEntity {
public String sku;
public int quantity;
@jakarta.persistence.ManyToOne
public Order order;
}
@ApplicationScoped
public class OrderRepository implements PanacheRepository<Order> {
// JOIN FETCH loads items in the same SELECT — no extra queries per order
public List<Order> findByCustomerWithItems(long customerId) {
return find("FROM Order o LEFT JOIN FETCH o.items WHERE o.customerId = ?1", customerId)
.list();
}
}
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
@ApplicationScoped
public class OrderRepository implements PanacheRepository<Order> {
public List<Order> findByCustomer(long customerId) {
return find("customerId", customerId).list();
}
}
// Bad: calling order.items for each order fires one SELECT per order
// 100 orders = 101 queries (N+1)
// Outside a session: LazyInitializationException
class OrderService {
void printSummaries(List<Order> orders) {
for (Order o : orders) {
System.out.println(o.items.size()); // each access triggers a lazy SELECT
}
}
}
```
### Example 9: @Version for optimistic locking
Title: Prevent silent lost updates under concurrency; handle OptimisticLockException at the service layer
Description: Adding `@Version` to an entity field causes Hibernate to append `AND version = ?` to every UPDATE and to increment the field on success. If a concurrent update has already changed the row, Hibernate throws `OptimisticLockException`. Catch it at the service layer and translate it to a meaningful domain response (e.g. HTTP 409 Conflict).
**Good example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.persistence.Entity;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.Version;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
@Entity
public class Product extends PanacheEntity {
public String name;
public BigDecimal price;
@Version
public long version; // Hibernate appends AND version=? to every UPDATE
}
@ApplicationScoped
public class ProductService {
@Transactional
public Product updatePrice(long productId, BigDecimal newPrice) {
Product p = Product.findById(productId);
if (p == null) {
throw new IllegalArgumentException("Product not found: " + productId);
}
p.price = newPrice;
// Hibernate flushes on transaction commit with WHERE id=? AND version=?
// OptimisticLockException thrown if a concurrent update won the race
return p;
}
}
// In REST resource — translate OptimisticLockException to HTTP 409
// @Provider public class OptimisticLockExceptionMapper implements ExceptionMapper<OptimisticLockException> { ... }
```
**Bad example:**
```java
import io.quarkus.hibernate.orm.panache.PanacheEntity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.Entity;
import jakarta.transaction.Transactional;
import java.math.BigDecimal;
// No @Version — two concurrent requests both read price=10.00, both update to different values,
// the last writer silently wins; neither request knows the other existed
@Entity
public class Product extends PanacheEntity {
public String name;
public BigDecimal price;
}
@ApplicationScoped
public class ProductService {
@Transactional
public void updatePrice(long productId, BigDecimal newPrice) {
Product p = Product.findById(productId);
if (p != null) {
p.price = newPrice; // silent lost update under concurrency
}
}
}
```
### Example 10: Testing with @QuarkusTest and @TestTransaction
Title: @TestTransaction rolls back after each test — no leftover data between tests
Description: Annotate each repository or service test with `@TestTransaction` so Quarkus wraps the test method in a transaction and rolls it back on completion. This keeps tests isolated without manual cleanup scripts. Use Dev Services (automatic container start) so tests run against a real database dialect.
**Good example:**
```java
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.TestTransaction;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@QuarkusTest
class BookRepositoryTest {
@Inject
BookRepository bookRepository;
@Test
@TestTransaction // wraps test in a transaction; rolled back on completion
void persist_and_findById_returnsBook() {
Book b = new Book();
b.title = "Quarkus Guide";
b.author = "Jane";
b.published = true;
bookRepository.persist(b);
Optional<Book> found = bookRepository.findByIdOptional(b.id);
assertThat(found).isPresent();
assertThat(found.get().title).isEqualTo("Quarkus Guide");
}
@Test
@TestTransaction
void findPublished_returnsOnlyPublishedBooks() {
Book draft = new Book();
draft.title = "Draft";
draft.author = "Bob";
draft.published = false;
bookRepository.persist(draft);
assertThat(bookRepository.findPublished()).noneMatch(bk -> bk.id.equals(draft.id));
}
}
```
**Bad example:**
```java
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
@QuarkusTest
class BookRepositoryTest {
@Inject
BookRepository bookRepository;
// Bad: no @TestTransaction — data written by this test persists in the database
// and can pollute subsequent tests; test execution order becomes load-bearing
@Test
void persist_and_find() {
Book b = new Book();
b.title = "Leaking Book";
b.author = "Alice";
bookRepository.persist(b); // never cleaned up
assertThat(bookRepository.count()).isGreaterThan(0);
}
}
```
## Output Format
- **ANALYZE** entities, repositories, and services for query injection risk, leaky entity boundaries, missing `@Transactional`, list queries without explicit pagination and result limits, lazy N+1 patterns, missing `@Version`, and absence of test isolation
- **CATEGORIZE** findings by impact (SECURITY for query injection, CORRECTNESS for missing transactions or N+1, PERFORMANCE for missing pagination or maximum page sizes, MAINTAINABILITY for entity exposure at API boundaries)
- **APPLY** improvements: introduce parameterized queries, `project(Class)` DTO projections, `page(Page.of(...))` pagination with an explicit maximum page size, `@NamedQuery` for stable queries, `JOIN FETCH` for needed associations, `@Version` for concurrency control
- **IMPLEMENT** changes consistently: keep entity, service, and REST resource layers coherent; update test fixtures when entity shape changes
- **EXPLAIN** trade-offs (active record vs repository, eager JOIN FETCH vs lazy, `project()` vs manual mapping, `@Version` vs DB-level locking)
- **TEST** persistence behaviour with `@QuarkusTest` + `@TestTransaction` using Dev Services for a realistic database dialect; never mock the repository inside persistence tests
- **VALIDATE** with `./mvnw compile` before and `./mvnw clean verify` after changes
## Safeguards
- **BLOCKING SAFETY CHECK**: ALWAYS run `./mvnw compile` before ANY Panache refactoring — compilation failure is a HARD STOP
- **CRITICAL VALIDATION**: Run `./mvnw clean verify` after changes; confirm persistence tests pass with Dev Services before promoting
- **QUERY SAFETY**: Never concatenate user input into JPQL, PanacheQL, or native SQL — use `?1`, `:name`, or `Parameters.with(...)` exclusively
- **ENTITY BOUNDARIES**: Do not return managed entities directly from REST resources — map to DTOs or use `project(Class)` to keep API contracts stable and prevent accidental field exposure
- **PAGINATION**: Never call `listAll()` or an unbound `list(query)` on production tables — always apply `.page(Page.of(index, size))` or a LIMIT clause
- **N+1 PREVENTION**: When a use case accesses collection associations on every returned entity, add `JOIN FETCH` to the JPQL query; lazy access outside a Hibernate session throws `LazyInitializationException`
- **OPTIMISTIC LOCKING**: Adding `@Version` to an existing entity requires a `version` column in the schema — apply via a migration (`@413-frameworks-quarkus-db-migrations-flyway`) before deploying; mismatched schema causes startup failure
- **CDI SELF-INVOCATION**: Never call a `@Transactional` method via `this.method()` within the same CDI bean — the interceptor is bypassed; extract to a separate injected bean
- **INCREMENTAL SAFETY**: Change one entity, repository, or service at a time; verify with `@QuarkusTest` + `@TestTransaction` between steps; do not combine aggregate boundary changes with query refactoring in one commitRelated skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |