Java Hibernate Jpa
GitHubOfficialFirst committed by jduboisDistributed by GitHub
- Skill
- Guidelines
- Software development
- MIT
- No issues found
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/java-hibernate-jpa/downloadUnzip 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
Read
pom.xml/build.gradle(or the dependency tree) forhibernate-coreand the persistence API:jakarta.persistence(Hibernate 6+/Jakarta EE 9+) vsjavax.persistence(Hibernate 5, seejavax-to-jakarta-migration).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+.Note the database and whether the schema is managed by Flyway/Liquibase.
Turn on SQL logging and statistics in a test (see
references/tooling-and-versions.md) before "optimizing" anything: measure statement counts.
Quick decision table
| Symptom | Likely cause | Go to |
|---|---|---|
| Many similar SELECTs for one request | N+1 on lazy association | references/fetching-and-n-plus-one.md |
LazyInitializationException | Lazy access outside session | references/fetching-and-n-plus-one.md |
HHH000104 / HHH90003004 warning, big memory use | Pagination with collection fetch join | references/queries-pagination-batching.md |
| Inserts slow, no JDBC batching | IDENTITY ids or batching not configured | references/identifiers-and-entity-design.md, references/queries-pagination-batching.md |
Duplicate rows / lost children / Set anomalies | Bad equals/hashCode or cascade misuse | references/identifiers-and-entity-design.md, references/associations-and-cascade.md |
| Lost updates, deadlocks | Missing locking strategy | references/locking-transactions-caching.md |
| Stale or surprising data with caches | Second-level/query cache misuse | references/locking-transactions-caching.md |
Schema drift, ddl-auto in prod | No migration tool | references/tooling-and-versions.md |
Top rules (apply during review)
Associations:
@ManyToOne/@OneToOnedefault to EAGER; declarefetch = FetchType.LAZYexplicitly.@OneToMany/@ManyToManyare LAZY by default and should stay so. Choose fetching per query (JOIN FETCH, entity graph), not by making mappings EAGER.Prefer
@ManyToOneowning side plus a bidirectional@OneToMany(mappedBy=...)only when needed; keep both sides in sync through helper methods.SetorListfor collections? UseSetfor@ManyToMany; a unidirectional@OneToManywith@JoinColumnorListwithout an order has costly update patterns.Never use
CascadeType.REMOVE/ALLon@ManyToOneor@ManyToMany. UseorphanRemovalonly on a true parent-owned child collection.Ids:
SEQUENCE(pooled optimizer,allocationSizematching the DB increment) for generated numeric ids;IDENTITYdisables JDBC insert batching; use UUIDs (time-ordered preferred) when ids must be generated client-side.Entities: no Lombok
@Data/@EqualsAndHashCode/@ToStringover associations; implementequals/hashCodedeliberately.Return DTOs/projections from read endpoints rather than entities; never expose entities (lazy proxies) directly in an API.
Paginate with a stable
ORDER BYincluding a unique tiebreaker; never combinesetMaxResultswith a collectionJOIN FETCH.Keep transactions short, at the service boundary; no remote calls or user interaction inside one.
Write and flush in batches for bulk work and clear the persistence context periodically.
Verify behavior with statement counts in tests against the real database engine.
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(orcreate-dropfor throwaway tests) is acceptable.Production (default): versioned migrations with Flyway or Liquibase, and
hibernate.hbm2ddl.auto=validate(ornone). Add them when the user wants versioned migrations or the app is headed to production.Externally managed schema:
none(orvalidate); 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
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md6.5 KiB
- references/associations-and-cascade.md4.4 KiB
- references/fetching-and-n-plus-one.md5.8 KiB
- references/identifiers-and-entity-design.md7.1 KiB
- references/locking-transactions-caching.md5.7 KiB
- references/queries-pagination-batching.md6.8 KiB
- references/tooling-and-versions.md6.1 KiB
references/identifiers-and-entity-design.md
Identifiers and entity design
Identifier generation
| Strategy | Batch inserts | Notes |
|---|---|---|
SEQUENCE | Yes | Best default on PostgreSQL, Oracle, SQL Server, MariaDB, H2, Db2. |
IDENTITY | No (Hibernate must execute each insert to get the id) | Use when the DB has no sequences (older MySQL); accept slower bulk inserts. |
TABLE | Yes but contended | Avoid. |
AUTO | Depends on dialect | Hibernate 6+ picks a sequence when the dialect supports it; be explicit. |
UUID | Yes | Client-generated; no round-trip. |
Sequence with pooled optimizer
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
private Long id;allocationSize(default 50) must equal the sequence'sINCREMENT BYin the database. A mismatch causes duplicate-key errors or wasteful gaps. Hibernate uses a pooled optimizer by default: one sequence call reservesallocationSizeids.Other applications or SQL scripts inserting rows must use the same increment, or draw ids from the sequence in a compatible way.
Create the sequence in the migration (
CREATE SEQUENCE order_seq START WITH 1 INCREMENT BY 50).
UUID
@Id
@GeneratedValue(strategy = GenerationType.UUID) // Jakarta Persistence 3.1+
private UUID id;Random v4 UUIDs fragment B-tree indexes on large tables; prefer time-ordered ids (UUIDv7) generated by the application or Hibernate's @UuidGenerator(style = UuidGenerator.Style.TIME) (Hibernate 6.x; check the docs of your version for the v7 option). Store as native uuid columns, not varchar(36).
Anti-patterns
IDENTITYon a table you bulk-load.Natural keys that change; use a surrogate id plus a unique constraint, or
@NaturalId.@GenericGenerator(Hibernate-specific, deprecated in 6.5+): use@SequenceGenerator,@UuidGenerator, or the newer id generator annotations documented for your version.
equals and hashCode
Problems: the id is null until persist; default identity equality breaks Set semantics across detached/merged instances; Hibernate proxies are subclasses, so getClass() comparisons fail.
Option A (generated id, recommended pattern):
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
Class<?> oClass = o instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisClass = this instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass() : getClass();
if (thisClass != oClass) return false; // proxy-safe, symmetric
Book other = (Book) o;
Object thisId = this instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getInternalIdentifier() : getId();
Object otherId = other instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getInternalIdentifier() : other.getId();
return thisId != null && thisId.equals(otherId);
}
@Override
public final int hashCode() {
return this instanceof HibernateProxy p
? p.getHibernateLazyInitializer().getPersistentClass().hashCode()
: getClass().hashCode(); // constant per persistent class; stable before/after persist
}Keep both methods final so Hibernate does not intercept them and initialize the proxy before the method body runs. Use getInternalIdentifier() for proxies: unlike getIdentifier() or an intercepted getId(), it does not initialize them even with JPA proxy compliance enabled. This is a Hibernate-specific pattern, not a provider-portable JPA recipe.
Constant hashCode is fine for entity sets of modest size (hundreds); large in-memory sets of entities are a design smell anyway. getClass() on a proxy returns the generated subclass, so both methods resolve the persistent class first (Hibernate.getClass(x) does the same but initializes the proxy). The class comparison keeps equals symmetric and consistent with hashCode; for entity hierarchies where a subclass should equal its parent type, compare against the root entity class instead.
Validate with two distinct transient books (not equal), the same book before/after persist (hash unchanged), and an uninitialized em.getReference(Book.class, id) after closing its entity manager. Adding that detached proxy to a HashSet, comparing it to a detached book with the same id in both directions, and calling contains must not throw or initialize the proxy. Also check zero additional SQL while the proxy is still attached, including with hibernate.jpa.compliance.proxy=true.
Option B (business/natural key): compare an immutable, unique attribute (ISBN, email), using getters. Implement hashCode on the same field. Mark it @NaturalId. Never use mutable fields.
Option C (client-assigned UUID id): compare/hash the UUID; it exists from construction.
Never include associations or lazy collections in equals/hashCode/toString.
Lombok on entities
Do not use
@Data,@EqualsAndHashCode,@ToString(default) on entities: they touch lazy collections (triggering loads orLazyInitializationException), cause infinite recursion in bidirectional associations, and makehashCodechange after persist.Use
@Getter/@Setterselectively (setters on collections and ids usually should not exist), and@ToString(onlyExplicitlyIncluded = true)with basic fields only.@Builderand@AllArgsConstructorbypass invariants and require a protected no-arg constructor (@NoArgsConstructor(access = AccessLevel.PROTECTED)); initialize collections with@Builder.Default.Entities must be non-final with a non-private no-arg constructor (Hibernate proxies); do not make fields
final.
Records vs entities
Java records cannot be entities: entities need a no-arg constructor, mutability, and non-final classes. (Hibernate 6+ does support records as
@Embeddablecomponents and as projection/DTO types.)Use records for DTOs, projections, and embeddables; keep entities as classes.
Enums and converters
@Enumerated(EnumType.STRING)(readable, resilient to reordering).ORDINALbreaks when constants are reordered or inserted.Add a DB check constraint or a native/PostgreSQL enum mapping if invalid values must be rejected at storage level.
Custom types:
AttributeConverter<X, Y>with@Converter(autoApply = false)and@Converton the attribute. Converters must be stateless and null-safe, and are not applied to ids or in some JPQL comparisons; test queries that compare converted attributes.Prefer
java.timetypes overjava.util.Date;Instant/OffsetDateTimewith UTC (hibernate.jdbc.time_zone=UTC).BigDecimalcolumns: setprecisionandscale.
Other design points
Embedded value objects with
@Embeddableinstead of loose columns.Use
@Versionfor optimistic locking on aggregate roots (locking-transactions-caching.md).Mark read-only reference entities
@Immutable.@ElementCollectionfor small value sets only; large or queried collections deserve their own entity.Prefer
Long/UUIDwrapper ids (null means transient).
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
jdubois
- 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