Generated banner for Java Hibernate Jpa
Generated logo for Java Hibernate Jpa

Java Hibernate Jpa

GitHubOfficialFirst committed by jduboisDistributed by GitHub

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

Diagnose and fix Hibernate ORM / Jakarta Persistence problems in plain Java: N+1 queries, lazy loading errors, identifier generation, entity equals/hashCode, cascades, pagination, batching, locking, caching, Lombok on entities, and Hibernate 6/7 differences. Use when reviewing or writing JPA entities, mappings, and queries. Framework-neutral.
— the description by jdubois

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to identifying and fixing common Hibernate ORM and Jakarta Persistence (JPA) issues. It covers entity mapping, association management, query optimization, and transaction handling. The content is framework-neutral, focusing on the behavior of the EntityManager, Session, JPQL/HQL, and mapping annotations across different Hibernate versions.

What it does

  • Detects N+1 query problems and provides optimization strategies like JOIN FETCH and batch fetching.
  • Provides rules for entity design, including identifier generation and equals/hashCode implementation.
  • Explains how to manage associations, cascades, and orphan removal to prevent data anomalies.
  • Offers guidance on schema management and versioned migrations.
  • Helps resolve LazyInitializationException and other common persistence errors.
  • Details differences between Hibernate versions and Jakarta Persistence specifications.

When to use it

  • When debugging performance issues related to database queries.
  • During code reviews of JPA entities and persistence logic.
  • When configuring Hibernate for new projects or upgrading between versions.
  • When encountering unexpected behavior in entity state management or transaction boundaries.

Advantages

  • Provides a clear decision table for common persistence symptoms.
  • Offers specific, actionable rules for mapping and association management.
  • Includes guidance on testing strategies to verify statement counts and behavior.
  • Maintains a framework-neutral perspective applicable to various Java environments.

Usage examples

“How do I fix an N+1 query issue in my Hibernate application?”
The agent will explain how to detect the issue using SQL logging and provide solutions such as JOIN FETCH, entity graphs, or batch fetching.
“What are the best practices for implementing equals and hashCode in JPA entities?”
The agent will provide rules for stable equality, warning against using generated IDs in hashCode and advising on Lombok usage with associations.
“How should I handle schema management in production with Hibernate?”
The agent will recommend using versioned migration tools like Flyway or Liquibase and setting hibernate.hbm2ddl.auto to validate or none.
“Why am I getting a LazyInitializationException?”
The agent will explain that the session has closed before the lazy association was accessed and suggest loading the required data within the transaction boundary.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/github/java-hibernate-jpa/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip java-hibernate-jpa.zip -d .agents/skills

Documentation by jdubois

Hibernate ORM and Jakarta Persistence

Problem -> anti-pattern -> fix library for entity mapping and querying. Framework-neutral: it covers EntityManager/Session behavior, JPQL/HQL, and mapping annotations. If the project uses Spring Boot and the java-springboot and spring-boot-testing skills are installed, use them for Spring Data repositories, transaction wiring, and @DataJpaTest; for Panache and reactive persistence see the Quarkus skills. Integration tests against a real database: java-testcontainers.

First: detect the stack

  1. Read pom.xml/build.gradle (or the dependency tree) for hibernate-core and the persistence API: jakarta.persistence (Hibernate 6+/Jakarta EE 9+) vs javax.persistence (Hibernate 5, see javax-to-jakarta-migration).

  2. Note the Hibernate major version; behavior differs (see references/tooling-and-versions.md). Hibernate 6.0-6.1 implement Jakarta Persistence 3.0, 6.2+ implement 3.1, 7.x implements 3.2, and Hibernate 7 needs Java 17+.

  3. Note the database and whether the schema is managed by Flyway/Liquibase.

  4. Turn on SQL logging and statistics in a test (see references/tooling-and-versions.md) before "optimizing" anything: measure statement counts.

Quick decision table

SymptomLikely causeGo to
Many similar SELECTs for one requestN+1 on lazy associationreferences/fetching-and-n-plus-one.md
LazyInitializationExceptionLazy access outside sessionreferences/fetching-and-n-plus-one.md
HHH000104 / HHH90003004 warning, big memory usePagination with collection fetch joinreferences/queries-pagination-batching.md
Inserts slow, no JDBC batchingIDENTITY ids or batching not configuredreferences/identifiers-and-entity-design.md, references/queries-pagination-batching.md
Duplicate rows / lost children / Set anomaliesBad equals/hashCode or cascade misusereferences/identifiers-and-entity-design.md, references/associations-and-cascade.md
Lost updates, deadlocksMissing locking strategyreferences/locking-transactions-caching.md
Stale or surprising data with cachesSecond-level/query cache misusereferences/locking-transactions-caching.md
Schema drift, ddl-auto in prodNo migration toolreferences/tooling-and-versions.md

Top rules (apply during review)

  1. Associations: @ManyToOne/@OneToOne default to EAGER; declare fetch = FetchType.LAZY explicitly. @OneToMany/@ManyToMany are LAZY by default and should stay so. Choose fetching per query (JOIN FETCH, entity graph), not by making mappings EAGER.

  2. Prefer @ManyToOne owning side plus a bidirectional @OneToMany(mappedBy=...) only when needed; keep both sides in sync through helper methods.

  3. Set or List for collections? Use Set for @ManyToMany; a unidirectional @OneToMany with @JoinColumn or List without an order has costly update patterns.

  4. Never use CascadeType.REMOVE/ALL on @ManyToOne or @ManyToMany. Use orphanRemoval only on a true parent-owned child collection.

  5. Ids: SEQUENCE (pooled optimizer, allocationSize matching the DB increment) for generated numeric ids; IDENTITY disables JDBC insert batching; use UUIDs (time-ordered preferred) when ids must be generated client-side.

  6. Entities: no Lombok @Data/@EqualsAndHashCode/@ToString over associations; implement equals/hashCode deliberately.

  7. Return DTOs/projections from read endpoints rather than entities; never expose entities (lazy proxies) directly in an API.

  8. Paginate with a stable ORDER BY including a unique tiebreaker; never combine setMaxResults with a collection JOIN FETCH.

  9. Keep transactions short, at the service boundary; no remote calls or user interaction inside one.

  10. Write and flush in batches for bulk work and clear the persistence context periodically.

  11. Verify behavior with statement counts in tests against the real database engine.

  12. Follow the schema management rule below.

Schema management rule

This is the single rule other skills refer to by name:

  • Prototype/local: hibernate.hbm2ddl.auto=update (or create-drop for throwaway tests) is acceptable.

  • Production (default): versioned migrations with Flyway or Liquibase, and hibernate.hbm2ddl.auto=validate (or none). Add them when the user wants versioned migrations or the app is headed to production.

  • Externally managed schema: none (or validate); do not add a migration tool.

Review focus

Check statement counts for N+1, explicit LAZY on to-one associations, sequence-based ids with matching allocationSize, and equals/hashCode stable across transient to persistent. Version-dependent details (Hibernate 5/6/7): references/tooling-and-versions.md.

References

  • references/fetching-and-n-plus-one.md: N+1 detection and fixes, lazy vs eager, LazyInitializationException, open-session-in-view, DTO projections.

  • references/identifiers-and-entity-design.md: id generation, equals/hashCode, Lombok, records vs entities, enums and converters, value types.

  • references/associations-and-cascade.md: bidirectional helpers, cascade, orphanRemoval, collection choice, @ManyToMany.

  • references/queries-pagination-batching.md: pagination (offset, keyset, in-memory warning), bulk operations, JDBC batching, StatelessSession.

  • references/locking-transactions-caching.md: optimistic/pessimistic locking, transaction boundaries, flush modes, second-level cache.

  • references/tooling-and-versions.md: SQL logging, statistics, tests, connection pool sizing, migrations, Hibernate 5/6/7 differences.

Canonical docs: Hibernate ORM user guide https://docs.hibernate.org/orm/current/userguide/html_single/ and Jakarta Persistence https://jakarta.ee/specifications/persistence/. Deep background articles: https://vladmihalcea.com/.

Upgrading (fetch the page for the target version; prefer it over this skill): migration guides https://hibernate.org/orm/documentation/migrate/ (6.6: https://docs.hibernate.org/orm/6.6/migration-guide/, 7.0: https://docs.hibernate.org/orm/7.0/migration-guide/), release notes https://hibernate.org/orm/releases/.

Files

references/fetching-and-n-plus-one.md

Fetching, N+1, lazy loading, projections

N+1 queries

Symptom: one query loads N parents, then one extra query per parent when a lazy association is touched (in code, in a JSON serializer, in toString).

Detect: enable SQL logging/statistics (tooling-and-versions.md) and assert the statement count in an integration test; look for repeated identical SELECTs differing only by id.

// anti-pattern: 1 + N
List<Order> orders = em.createQuery("select o from Order o", Order.class).getResultList();
orders.forEach(o -> o.getLines().size());
Fix 1: JOIN FETCH (query-specific)
List<Order> orders = em.createQuery(
    "select o from Order o left join fetch o.lines", Order.class)
  .getResultList();
  • Fetch many-to-one/one-to-one freely. Fetch at most one collection per query: two bag collections in one query throw MultipleBagFetchException (and joining several collections multiplies rows). Fetch the second collection in a second query on the same session; the persistence context stitches them together.

  • Hibernate 6+ de-duplicates root entities of fetch joins automatically, so DISTINCT is no longer needed for that; on Hibernate 5 add DISTINCT (consider the hibernate.query.passDistinctThrough hint to keep it out of SQL).

  • Do not paginate a collection fetch join (see queries-pagination-batching.md).

Fix 2: Entity graph (reusable fetch plan)
EntityGraph<Order> g = em.createEntityGraph(Order.class);
g.addAttributeNodes("customer");
g.addSubgraph("lines").addAttributeNodes("product");

List<Order> orders = em.createQuery("select o from Order o", Order.class)
  .setHint("jakarta.persistence.fetchgraph", g)   // Hibernate 7: prefer query.setEntityGraph(g, GraphSemantic.FETCH)
  .getResultList();

@NamedEntityGraph declares graphs on the entity. Fetch graph (fetchgraph) treats unlisted attributes as lazy; load graph (loadgraph) keeps mapping defaults.

Fix 3: Batch fetching (when you cannot know the access pattern)

Loads lazy associations of many parents with one IN (...) query instead of N queries.

@OneToMany(mappedBy = "order")
@BatchSize(size = 25)
private List<OrderLine> lines;

Global default: hibernate.default_batch_fetch_size=16 (values of 8-32 are typical). Turns N+1 into 1 + N/size. It also helps lazy @ManyToOne proxies. Not as precise as JOIN FETCH, but a good safety net.

Fix 4: Subselect fetching

@Fetch(FetchMode.SUBSELECT) loads the collection for all parents of the original query in one extra query. Good for small result sets of a single known query; can be heavy if the original query is expensive.

Fix 5: Projection that avoids entities

If the caller needs a flat view, select exactly the columns (below).

Lazy vs eager

  • Defaults: @ManyToOne, @OneToOne EAGER; @OneToMany, @ManyToMany, @ElementCollection LAZY; @Basic EAGER (@Lob and @Basic(fetch = LAZY) need bytecode enhancement to be really lazy).

  • FetchType.EAGER in a mapping applies to every load: em.find joins it, but JPQL/criteria queries ignore it for the initial SQL and load eager associations with follow-up selects (a hidden N+1). Set LAZY in the mapping and fetch per use case.

  • Lazy @OneToOne on the inverse side (mappedBy) is normally loaded eagerly because Hibernate must query to detect null; it can be a lazy proxy only with optional = false (the row is guaranteed to exist) or bytecode enhancement. Prefer a unidirectional owning side; @MapsId on the owning side does not by itself solve null detection for an optional inverse side.

  • Hibernate proxies: use Hibernate.initialize(x), Hibernate.isInitialized(x), and em.getReference (id-only reference to set a foreign key without a SELECT).

LazyInitializationException

Cause: a lazy association or proxy is accessed after the session closed (typically while serializing an entity in a controller).

Fixes, best first:

  1. Load what the use case needs inside the transaction (JOIN FETCH / entity graph / projection) and map to a DTO inside the transactional service method.

  2. Initialize explicitly in the service (Hibernate.initialize), only when the small count is known.

  3. Avoid hibernate.enable_lazy_load_no_trans=true: it opens a new connection per lazy load outside any transaction and hides N+1.

Open session in view (OSIV)

OSIV keeps the persistence context (and a database connection) open until the HTTP response is written, so lazy loading "works" in controllers and serializers.

Tradeoffs:

  • Pros: no LazyInitializationException in the view layer.

  • Cons: connection held during rendering and any remote call (pool starvation), queries issued from the view layer escape transaction/service design, hidden N+1, and with auto-commit-less modes extra statements outside the transaction.

  • Recommendation: disable OSIV where the framework enables it by default, return DTOs, and define fetch plans in the service layer. If kept, monitor connection hold time. Enabling/disabling is framework configuration (see java-springboot for Spring's spring.jpa.open-in-view).

DTO projections

Use them for read models, lists, reports. They skip dirty checking and snapshot memory.

public record OrderSummary(Long id, String customerName, BigDecimal total) {}

List<OrderSummary> rows = em.createQuery(
    "select new com.acme.OrderSummary(o.id, c.name, o.total) from Order o join o.customer c",
    OrderSummary.class).getResultList();
  • JPQL constructor expressions (select new ...) require the fully-qualified class name; alternatively select columns into Tuple.

  • Java records work as projection types with constructor expressions.

  • Native queries: @SqlResultSetMapping with @ConstructorResult, or Tuple.

  • Projections cannot be lazily loaded later; include everything the caller needs.

  • Entities are still right for write paths: load, change, let dirty checking flush.

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs network access

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of jduboisjdubois
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/java-hibernate-jpa · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
jdubois

AutoGineer is not affiliated with or endorsed by jdubois or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download java-hibernate-jpa.zip