Java Hibernate and JPA Fixes

Java Hibernate and JPA Fixes

Diagnoses and fixes Hibernate and Jakarta Persistence problems such as N+1 queries, lazy loading, cascades, batching and locking, with a problem-to-fix reference library.

Skill files7 files

references/

SKILL.md69 lines
1
---
2
name: java-hibernate-jpa
3
description: '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.'
4
---
5
6
# Hibernate ORM and Jakarta Persistence
7
8
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`.
9
10
## First: detect the stack
11
12
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`).
13
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+.
14
3. Note the database and whether the schema is managed by Flyway/Liquibase.
15
4. Turn on SQL logging and statistics in a test (see `references/tooling-and-versions.md`) before "optimizing" anything: measure statement counts.
16
17
## Quick decision table
18
19
| Symptom | Likely cause | Go to |
20
| --- | --- | --- |
21
| Many similar SELECTs for one request | N+1 on lazy association | `references/fetching-and-n-plus-one.md` |
22
| `LazyInitializationException` | Lazy access outside session | `references/fetching-and-n-plus-one.md` |
23
| `HHH000104` / `HHH90003004` warning, big memory use | Pagination with collection fetch join | `references/queries-pagination-batching.md` |
24
| Inserts slow, no JDBC batching | `IDENTITY` ids or batching not configured | `references/identifiers-and-entity-design.md`, `references/queries-pagination-batching.md` |
25
| Duplicate rows / lost children / `Set` anomalies | Bad `equals`/`hashCode` or cascade misuse | `references/identifiers-and-entity-design.md`, `references/associations-and-cascade.md` |
26
| Lost updates, deadlocks | Missing locking strategy | `references/locking-transactions-caching.md` |
27
| Stale or surprising data with caches | Second-level/query cache misuse | `references/locking-transactions-caching.md` |
28
| Schema drift, `ddl-auto` in prod | No migration tool | `references/tooling-and-versions.md` |
29
30
## Top rules (apply during review)
31
32
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.
33
2. Prefer `@ManyToOne` owning side plus a bidirectional `@OneToMany(mappedBy=...)` only when needed; keep both sides in sync through helper methods.
34
3. `Set` or `List` for collections? Use `Set` for `@ManyToMany`; a unidirectional `@OneToMany` with `@JoinColumn` or `List` without an order has costly update patterns.
35
4. Never use `CascadeType.REMOVE`/`ALL` on `@ManyToOne` or `@ManyToMany`. Use `orphanRemoval` only on a true parent-owned child collection.
36
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.
37
6. Entities: no Lombok `@Data`/`@EqualsAndHashCode`/`@ToString` over associations; implement `equals`/`hashCode` deliberately.
38
7. Return DTOs/projections from read endpoints rather than entities; never expose entities (lazy proxies) directly in an API.
39
8. Paginate with a stable `ORDER BY` including a unique tiebreaker; never combine `setMaxResults` with a collection `JOIN FETCH`.
40
9. Keep transactions short, at the service boundary; no remote calls or user interaction inside one.
41
10. Write and flush in batches for bulk work and clear the persistence context periodically.
42
11. Verify behavior with statement counts in tests against the real database engine.
43
12. Follow the schema management rule below.
44
45
## Schema management rule
46
47
This is the single rule other skills refer to by name:
48
49
- **Prototype/local:** `hibernate.hbm2ddl.auto=update` (or `create-drop` for throwaway tests) is acceptable.
50
- **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.
51
- **Externally managed schema:** `none` (or `validate`); do not add a migration tool.
52
53
## Review focus
54
55
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`.
56
57
## References
58
59
- `references/fetching-and-n-plus-one.md`: N+1 detection and fixes, lazy vs eager, `LazyInitializationException`, open-session-in-view, DTO projections.
60
- `references/identifiers-and-entity-design.md`: id generation, `equals`/`hashCode`, Lombok, records vs entities, enums and converters, value types.
61
- `references/associations-and-cascade.md`: bidirectional helpers, cascade, `orphanRemoval`, collection choice, `@ManyToMany`.
62
- `references/queries-pagination-batching.md`: pagination (offset, keyset, in-memory warning), bulk operations, JDBC batching, `StatelessSession`.
63
- `references/locking-transactions-caching.md`: optimistic/pessimistic locking, transaction boundaries, flush modes, second-level cache.
64
- `references/tooling-and-versions.md`: SQL logging, statistics, tests, connection pool sizing, migrations, Hibernate 5/6/7 differences.
65
66
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/>.
67
68
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/>.
69

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…