agentleFS
piominpiomin/claude-ai-quarkus/skills/jpa-patterns/SKILL.md

jpa-patterns

Skill7 starsChanged 23 days agoApache-2.0View on GitHub

JPA/Hibernate patterns and common pitfalls (N+1, lazy loading, transactions, queries) for Quarkus/Panache. Use when user has JPA performance issues, LazyInitializationException, or asks about entity relationships and fetching strategies.

25 other projects use a version of this, 4 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use nuxt4-patterns, agent-payment-x402 and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • loulanyueSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 10 projects that use this

  • TironFoxSkill

    agent-payment-x402

    Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.

    Also in 6 projects that use this

  • TironFoxSkill

    openclaw-persona-forge

    为 OpenClaw AI Agent 锻造完整的龙虾灵魂方案。根据用户偏好或随机抽卡, 输出身份定位、灵魂描述(SOUL.md)、角色化底线规则、名字和头像生图提示词。 如当前环境提供已审核的生图 skill,可自动生成统一风格头像图片。 当用户需要创建、设计或定制 OpenClaw 龙虾灵魂时使用。 不适用于:微调已有 SOUL.md、非 OpenClaw 平台的角色设计、纯工具型无性格 Agent。 触发词:龙虾灵魂、虾魂、OpenClaw 灵魂、养虾灵魂、龙虾角色、龙虾定位、 龙虾剧本杀角色、龙虾游戏角色、龙虾 NPC、龙虾性格、龙虾背景故事、 lobster soul、lobster character、抽卡、随机龙虾、龙虾 SOUL、gacha。

    Also in 5 projects that use this

  • royaluniondesign-sysSkill

    configure-ecc

    Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.

    Also in 11 projects that use this

  • junimnjwSkill

    ralphinho-rfc-pipeline

    RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.

    Also in 10 projects that use this

  • RojiosSkill

    dart-flutter-patterns

    Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.

    Also in 6 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 21 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use instanceof, not getClass(), in equals so Hibernate proxies compare equal.

    line 388
  2. Very specific:

    No lifecycle callbacks (@PreUpdate), no cascades, no @Version check — increment the version in the query (version = version + 1) if …

    line 499

“Common” is measured: kept by at least 6 in 10 of the 21 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

JPA Patterns Skill

Best practices and common pitfalls for JPA/Hibernate in Quarkus applications (Hibernate ORM with Panache).

When to Use

  • User mentions "N+1 problem" / "too many queries"
  • LazyInitializationException errors
  • Questions about fetch strategies (EAGER vs LAZY)
  • Transaction management issues
  • Entity relationship design
  • Query optimization
  • Entity equals()/hashCode() and bulk UPDATE/DELETE queries

Quick Reference: Common Problems

ProblemSymptomSolution
N+1 queriesMany SELECT statementsJOIN FETCH, entity graphs
LazyInitializationExceptionError outside transactionJOIN FETCH, DTO projection, keep access inside @Transactional
Slow queriesPerformance issuesPagination, projections, indexes
Dirty checking overheadSlow updatesAvoid unnecessary @Transactional, use DTOs for pure reads
Lost updatesConcurrent modificationsOptimistic locking (@Version)
Entity lost from a HashSetequals/hashCode on generated id or all fieldsNatural key, or id-based with constant hashCode
Missing foreign key / stale collectionOnly one side of a bidirectional link updatedadd*/remove* helpers on the parent
Parent deleted with a childCascadeType.ALL on @ManyToOneCascade parent → children only
Stale entities after bulk queryBulk update/delete skips the persistence contextflush() before, clear() after

N+1 Problem

The #1 JPA performance killer

The Problem

// ❌ BAD: N+1 queries
@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
    private List<Book> books;
}

// This innocent code...
List<Author> authors = authorRepository.listAll();  // 1 query
for (Author author : authors) {
    System.out.println(author.getBooks().size());   // N queries!
}
// Result: 1 + N queries (if 100 authors = 101 queries)

Solution 1: JOIN FETCH (JPQL)

// ✅ GOOD: Single query with JOIN FETCH
@ApplicationScoped
public class AuthorRepository implements PanacheRepository<Author> {

    public List<Author> findAllWithBooks() {
        return getEntityManager()
            .createQuery("SELECT DISTINCT a FROM Author a JOIN FETCH a.books", Author.class)
            .getResultList();
    }
}

// Usage - single query
List<Author> authors = authorRepository.findAllWithBooks();

Solution 2: Named Entity Graph

// ✅ GOOD: Entity graph for declarative fetching (pure JPA/Hibernate feature)
@Entity
@NamedEntityGraph(
    name = "Author.withBooks",
    attributeNodes = @NamedAttributeNode("books")
)
public class Author {
    // ...
}

@ApplicationScoped
public class AuthorRepository implements PanacheRepository<Author> {

    public List<Author> findAllWithBooksViaGraph() {
        EntityGraph<?> graph = getEntityManager().getEntityGraph("Author.withBooks");
        return getEntityManager()
            .createQuery("SELECT a FROM Author a", Author.class)
            .setHint("jakarta.persistence.loadgraph", graph)
            .getResultList();
    }
}

Solution 3: Batch Fetching

// ✅ GOOD: Batch fetching (Hibernate-specific)
@Entity
public class Author {

    @OneToMany(mappedBy = "author")
    @BatchSize(size = 25)  // Fetch 25 at a time
    private List<Book> books;
}
# Or globally in application.properties
quarkus.hibernate-orm.fetch.batch-size=25

Detecting N+1

# application.properties - enable SQL logging to detect N+1
# (build-time property - requires a rebuild to toggle)
quarkus.hibernate-orm.log.sql=true
quarkus.hibernate-orm.log.format-sql=true
quarkus.hibernate-orm.log.bind-parameters=true

# Runtime alternative - toggle without rebuilding
quarkus.log.category."org.hibernate.SQL".level=DEBUG

Lazy Loading

FetchType Basics

@Entity
public class Order {

    // LAZY: Load only when accessed (default for collections)
    @OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
    private List<OrderItem> items;

    // EAGER: Always load immediately (default for @ManyToOne, @OneToOne)
    @ManyToOne(fetch = FetchType.EAGER)  // ⚠️ Usually bad
    private Customer customer;
}

Best Practice: Default to LAZY

// ✅ GOOD: Always use LAZY, fetch when needed
@Entity
public class Order {

    @ManyToOne(fetch = FetchType.LAZY)  // Override EAGER default
    private Customer customer;

    @OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
    private List<OrderItem> items;
}

LazyInitializationException

// ❌ BAD: Accessing lazy field outside transaction
@ApplicationScoped
public class OrderService {

    public Order getOrder(Long id) {
        return orderRepository.findById(id);
    }
}

// In a REST resource (no transaction)
Order order = orderService.getOrder(1L);
order.getItems().size();  // 💥 LazyInitializationException!

Solutions for LazyInitializationException

Solution 1: JOIN FETCH in query

// ✅ Fetch needed associations in query
public Optional<Order> findByIdWithItems(Long id) {
    return getEntityManager()
        .createQuery("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id", Order.class)
        .setParameter("id", id)
        .getResultStream()
        .findFirst();
}

Solution 2: @Transactional on service method

// ✅ Keep transaction open while accessing
@ApplicationScoped
public class OrderService {

    @Transactional
    public OrderDTO getOrderWithItems(Long id) {
        Order order = orderRepository.findByIdOptional(id).orElseThrow();
        // Access within transaction - lazy collection loads here
        int itemCount = order.getItems().size();
        return new OrderDTO(order, itemCount);
    }
}

Quarkus's @Transactional (jakarta.transaction.Transactional) has no readOnly attribute and no built-in read-only optimization hint.

Solution 3: DTO projection (best for read-only)

// ✅ Avoid lazy loading entirely - query only what you need
public Optional<OrderSummary> findSummaryById(Long id) {
    return getEntityManager()
        .createQuery("SELECT new com.example.dto.OrderSummary(o.id, o.status, SIZE(o.items)) " +
                     "FROM Order o WHERE o.id = :id", OrderSummary.class)
        .setParameter("id", id)
        .getResultStream()
        .findFirst();
}

Transaction Management

Read-Only Optimization

@ApplicationScoped
public class ProductService {
    private final ProductRepository repo;

    public ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    public List<Product> findAll() {
        return repo.listAll();  // Plain read: no @Transactional needed for a single operation
    }

    @Transactional  // Required for multi-step writes
    public Product create(ProductRequest request) {
        var product = new Product();
        product.setName(request.name());
        repo.persist(product);
        return product;
    }
}

A single Panache call outside an active transaction runs in its own implicit transaction automatically — you only need @Transactional explicitly for multi-step writes, or to keep a lazy association reachable across several calls.

Self-Invocation and Interceptors

Quarkus supports intercepted self-invocation: a call through this to a non-private method annotated with @Transactional (or any interceptor binding) is intercepted, so a transaction starts. This is a Quarkus (ArC) feature; the CDI specification leaves it undefined, so code shared with another CDI runtime should not rely on it.

@ApplicationScoped
public class OrderService {

    public void processOrders(List<Long> ids) {
        for (Long id : ids) {
            processOrder(id);  // intercepted in Quarkus: each call runs in its own transaction
        }
    }

    @Transactional
    public void processOrder(Long id) {
        // ...
    }
}

Pitfalls that remain:

  • An interceptor binding on a private method fails the build by default (quarkus.arc.fail-on-intercepted-private-method=true); make the method package-private or public.
  • Each self-invoked @Transactional call uses the default REQUIRED semantics: if the caller is already transactional, the calls join its transaction instead of committing one by one. Use @Transactional(REQUIRES_NEW) when each item must commit independently.
  • Extracting the transactional method into a separate bean is still a valid design choice when it clarifies responsibilities, but it is not required for interception.

See the CDI reference: intercepted self-invocation.


Optimistic Locking

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private BigDecimal price;

    @Version
    private Long version;  // Hibernate checks this on update

    // getters/setters
}

// Handling optimistic lock failure
@ApplicationScoped
public class ProductService {
    private final ProductRepository repo;

    public ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    @Transactional
    public Product updatePrice(Long id, BigDecimal newPrice) {
        Product product = repo.findByIdOptional(id)
            .orElseThrow(() -> new EntityNotFoundException("Product not found"));
        product.setPrice(newPrice);
        try {
            repo.flush();  // Force the version check now instead of at commit
            return product;
        } catch (OptimisticLockException e) {
            throw new ClientErrorException("Product was modified by another user", Response.Status.CONFLICT);
        }
    }
}

Entity Identity: equals() and hashCode()

// ✅ GOOD: Business key - stable before and after persist
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NaturalId  // org.hibernate.annotations.NaturalId
    @Column(unique = true, nullable = false, updatable = false)
    private String isbn;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        return o instanceof Book other && isbn != null && isbn.equals(other.isbn);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(isbn);
    }
}

// ✅ GOOD: No natural key - id-based equality, constant hashCode
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    return o instanceof Order other && id != null && id.equals(other.id);
}

@Override
public int hashCode() {
    return getClass().hashCode();  // Unchanged when the id is assigned on persist
}
  • ❌ Never hash the generated id (the entity "disappears" from a HashSet after persist) or all fields (mutable fields change the hash, lazy associations trigger loads).
  • Use instanceof, not getClass(), in equals so Hibernate proxies compare equal.

Relationship Mapping

Bidirectional Helpers

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();

    // ✅ Keep both sides in sync - the @ManyToOne side owns the foreign key
    public void addBook(Book book) {
        books.add(book);
        book.setAuthor(this);
    }

    public void removeBook(Book book) {
        books.remove(book);
        book.setAuthor(null);
    }

    public List<Book> getBooks() {
        return Collections.unmodifiableList(books);  // Force callers through the helpers
    }
}

Updating only one side leaves the in-memory graph inconsistent, and if only the inverse (mappedBy) side is set, the foreign key is never written.

@ManyToMany: Use a Set

@Entity
public class Student {
    @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE })  // Never REMOVE/ALL
    @JoinTable(name = "student_course",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id"))
    private Set<Course> courses = new HashSet<>();

    public void addCourse(Course course) {
        courses.add(course);
        course.getStudents().add(this);
    }

    public void removeCourse(Course course) {
        courses.remove(course);
        course.getStudents().remove(this);
    }
}

With a List, Hibernate deletes and re-inserts the whole join table on every change. A Set needs the stable equals()/hashCode() above. If the link carries data (enrolment date, grade), map the join table as its own entity with two @ManyToOnes.

Common Mapping Mistakes

// ❌ BAD: Cascade on @ManyToOne - removing one book removes the shared author
@ManyToOne(cascade = CascadeType.ALL)
private Author author;

// ✅ GOOD: Cascade only from parent to owned children
@ManyToOne(fetch = FetchType.LAZY)
private Author author;
// ❌ BAD: toString() touching a lazy collection - extra query,
// LazyInitializationException outside a transaction, StackOverflowError on bidirectional links
@Override
public String toString() {
    return "Author{id=" + id + ", books=" + books + "}";
}

// ✅ GOOD: Basic columns only
@Override
public String toString() {
    return "Author{id=" + id + ", name='" + name + "'}";
}

The same applies to logging an entity and to JSON serialization: map to DTOs/records instead.


Bulk Updates and Deletes

@ApplicationScoped
public class OrderRepository implements PanacheRepository<Order> {

    public int archiveOlderThan(Instant before) {
        return update("status = ?1 where createdAt < ?2", OrderStatus.ARCHIVED, before);
    }

    public long purge(OrderStatus status, Instant before) {
        return delete("status = ?1 and createdAt < ?2", status, before);
    }
}

Panache update(...)/delete(...) run a single bulk statement in the database. They must run inside @Transactional, and they bypass the persistence context:

  • No lifecycle callbacks (@PreUpdate), no cascades, no @Version check — increment the version in the query (version = version + 1) if concurrent writers rely on optimistic locking.
  • Entities already loaded in the same transaction keep their old state. If the transaction reads them again, call getEntityManager().flush() before the bulk statement and getEntityManager().clear() after it.

Modern Hibernate Features

Jakarta Persistence

// Always use jakarta.persistence.* (not javax.persistence.*)
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

UUID Generation

@Entity
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)  // Native UUID generation
    private UUID id;

    private String name;

    // getters/setters
}

Soft Delete

// Built-in soft delete support (Hibernate ORM 6.4+)
@Entity
@SoftDelete  // Adds 'deleted' boolean column, filters automatically
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    // getters/setters
}

// Custom column name
@Entity
@SoftDelete(columnName = "is_active", converter = NumericBooleanConverter.class)
public class Product {
    // ...
}

Record as DTO in Queries

// Records work natively in JPQL constructor expressions
public record ProductSummary(Long id, String name, BigDecimal price) {}

@ApplicationScoped
public class ProductRepository implements PanacheRepository<Product> {

    public List<ProductSummary> findExpensiveProducts(BigDecimal minPrice) {
        return getEntityManager()
            .createQuery("SELECT new com.example.dto.ProductSummary(p.id, p.name, p.price) " +
                         "FROM Product p WHERE p.price > :minPrice", ProductSummary.class)
            .setParameter("minPrice", minPrice)
            .getResultList();
    }
}

Query Best Practices

Pagination

// ✅ Always paginate unbounded queries
@ApplicationScoped
public class UserRepository implements PanacheRepository<User> {

    public List<User> findActive(int pageIndex, int pageSize) {
        return find("active", Sort.by("createdAt").descending(), true)
            .page(Page.of(pageIndex, pageSize))
            .list();
    }
}

// Usage
List<User> users = userRepository.findActive(0, 20);
long totalCount = userRepository.count("active", true);

DTO / Record Projections

// ✅ Fetch only the columns you need via a JPQL constructor expression
public record UserNameOnly(String firstName, String lastName) {}

@ApplicationScoped
public class UserRepository implements PanacheRepository<User> {

    public List<UserNameOnly> findAllActiveNames() {
        return getEntityManager()
            .createQuery("SELECT new com.example.dto.UserNameOnly(u.firstName, u.lastName) " +
                         "FROM User u WHERE u.active = true", UserNameOnly.class)
            .getResultList();
    }
}

Quick Decision Guide

SituationSolution
N+1 in loopJOIN FETCH or named entity graph
LazyInitializationExceptionJOIN FETCH in query or @Transactional on service
Read-only queries slowAvoid @Transactional on single reads; use DTO projections
Concurrent updates@Version + optimistic locking
Unbounded result setPagination with Panache Page.of()
Need only few columnsDTO/record projection (JPQL constructor expression)
Soft delete required@SoftDelete
UUID primary key@GeneratedValue(strategy = GenerationType.UUID)
@ManyToMany collectionSet + helper methods, cascade PERSIST/MERGE only
Mass update/deletePanache update(...)/delete(...) in @Transactional

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.