Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install java-hibernate-jpa@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin java-hibernate-jpa v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install java-hibernate-jpa

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/java-hibernate-jpa/

Extract the ZIP to .github/skills/ in your repo. The folder name must match java-hibernate-jpa for Copilot to auto-discover it.

Skill Files (7)

SKILL.md 6.5 KB
---
name: java-hibernate-jpa
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.'
---

# 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

| 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)

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/>.
references/
associations-and-cascade.md 4.4 KB
# Associations, cascade, collections

## Bidirectional associations with helpers

The owning side holds the foreign key (`@ManyToOne`). The inverse side uses `mappedBy`. Keep both sides in sync in the domain model, otherwise the in-memory graph and the database diverge.

```java
@Entity
class Order {
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    public void addLine(OrderLine line) {
        lines.add(line);
        line.setOrder(this);
    }

    public void removeLine(OrderLine line) {
        lines.remove(line);
        line.setOrder(null);
    }

    public List<OrderLine> getLines() {
        return Collections.unmodifiableList(lines);
    }
}

@Entity
class OrderLine {
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "order_id")
    private Order order;
}
```

Rules:
- Only the `@ManyToOne` side writes the FK; changing only the inverse collection does nothing to the database.
- Expose the collection read-only (or defensively copied); initialize it once and never replace the reference (`order.setLines(new ArrayList<>())` breaks orphan removal and confuses Hibernate's collection tracking: mutate with `clear()`/`add()`).
- Prefer unidirectional `@ManyToOne` and query the many side when you never navigate parent -> children.

## Unidirectional @OneToMany anti-pattern

A `@OneToMany` without `mappedBy` and without `@JoinColumn` creates a join table and extra SQL. With `@JoinColumn` it issues an `INSERT` then an `UPDATE` for the FK. Make the relationship bidirectional (or `@ManyToOne` only).

## Cascade pitfalls

| Pitfall | Fix |
| --- | --- |
| `CascadeType.ALL`/`REMOVE` on `@ManyToOne` or `@ManyToMany`: deleting one child deletes the shared parent or related rows | Cascade only parent -> owned child. |
| `CascadeType.REMOVE` for a large collection loads and deletes row by row | Flush pending changes, execute a bulk `DELETE ... WHERE parent_id = :id`, then clear the context; alternatively use DB `ON DELETE CASCADE` with `@OnDelete(action = OnDeleteAction.CASCADE)`. |
| `CascadeType.PERSIST` on a detached child: `PersistentObjectException: detached entity passed to persist` | Use `merge` (or load the entity first); do not set a detached instance on a persist-cascaded association. |
| `CascadeType.MERGE` overwrites state with stale DTO data | Copy only allowed fields onto a managed entity. |
| `orphanRemoval = true` on a shared child | Only for exclusive, parent-owned children; removing from the collection deletes the row. |
| Replacing a collection with `setX(newList)` on an `orphanRemoval` mapping | `A collection with cascade="all-delete-orphan" was no longer referenced`; mutate in place. |

`orphanRemoval` also implies removal when the parent is removed.

## Collection type choice

- `@ManyToMany`: use `Set`. With a `List` (a bag), removing one element deletes **all** join-table rows and re-inserts the rest.
- Avoid `@ManyToMany` for anything beyond a plain link; model the join as an entity (with `@ManyToOne` on both sides) as soon as it has attributes or you query it.
- `@OneToMany` `List` with `@OrderColumn` rewrites index columns on removal from the head; use `@OrderBy` for read-time ordering instead.
- Collections with possibly thousands of rows should not be mapped at all; query them with pagination.
- Never call `collection.size()` or `contains()` on a large lazy collection to count/check; run a count/exists query (`@LazyCollection(EXTRA)` is deprecated).

## Equality in collections

`Set` semantics rely on `equals`/`hashCode` (see `identifiers-and-entity-design.md`). A `HashSet` of entities whose `hashCode` depends on the generated id will lose elements after `persist`.

## One-to-one

Prefer a shared primary key (`@MapsId`) for a true one-to-one: no extra index, lazy-loadable from the owning side, and one-query `find`. Without it, the inverse side (`mappedBy`) is usually loaded eagerly, because Hibernate must query to know whether it is null; it can be a lazy proxy only when `optional = false` guarantees the row exists, or with bytecode enhancement.

## Delete and update patterns

- Removing a parent with children: either cascade REMOVE (small, owned collections), DB-level cascade, or explicit bulk delete in order (children first).
- Bulk JPQL/HQL `update`/`delete` bypass the persistence context and version columns; flush before, and `clear()` afterwards or refresh entities.
fetching-and-n-plus-one.md 5.8 KB
# 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.

```java
// 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)

```java
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)

```java
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.

```java
@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.

```java
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.
identifiers-and-entity-design.md 7.1 KB
# 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

```java
@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's `INCREMENT BY` in the database. A mismatch causes duplicate-key errors or wasteful gaps. Hibernate uses a pooled optimizer by default: one sequence call reserves `allocationSize` ids.
- 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

```java
@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

- `IDENTITY` on 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):

```java
@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 or `LazyInitializationException`), cause infinite recursion in bidirectional associations, and make `hashCode` change after persist.
- Use `@Getter`/`@Setter` selectively (setters on collections and ids usually should not exist), and `@ToString(onlyExplicitlyIncluded = true)` with basic fields only.
- `@Builder` and `@AllArgsConstructor` bypass 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 `@Embeddable` components 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). `ORDINAL` breaks 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 `@Convert` on 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.time` types over `java.util.Date`; `Instant`/`OffsetDateTime` with UTC (`hibernate.jdbc.time_zone=UTC`).
- `BigDecimal` columns: set `precision` and `scale`.

## Other design points

- Embedded value objects with `@Embeddable` instead of loose columns.
- Use `@Version` for optimistic locking on aggregate roots (`locking-transactions-caching.md`).
- Mark read-only reference entities `@Immutable`.
- `@ElementCollection` for small value sets only; large or queried collections deserve their own entity.
- Prefer `Long`/`UUID` wrapper ids (null means transient).
locking-transactions-caching.md 5.7 KB
# Locking, transactions, caching

## Optimistic locking (default choice)

```java
@Entity
class Account {
    @Version
    private long version;
}
```

- Hibernate adds `WHERE version = ?` to updates; a concurrent change throws `OptimisticLockException` (Hibernate: `StaleObjectStateException`). Catch it at the use-case boundary, then retry or tell the user to reload.
- Use `Integer`/`Long`/`Instant` version types; never modify the version manually.
- With DTO round-trips (web forms), send the version to the client and, on submit, load the entity (`em.find`), compare the submitted version with the loaded one and reject a mismatch (e.g. HTTP 409). Never assign the client's version to a managed entity: Jakarta Persistence forbids applications from changing the version. Alternatively `merge()` a detached entity that carries its `@Version`; the provider then checks it and throws `OptimisticLockException` on a stale one, which you handle at the use-case boundary.
- `LockModeType.OPTIMISTIC_FORCE_INCREMENT` bumps the version even if only children changed, useful for aggregate roots.
- Bulk HQL updates ignore `@Version` unless you write `update versioned`.

## Pessimistic locking

Use for hot rows or queue-like tables where retries are too costly.

```java
Account a = em.find(Account.class, id, LockModeType.PESSIMISTIC_WRITE,
    Map.of("jakarta.persistence.lock.timeout", 3000));
```

- `PESSIMISTIC_WRITE` -> `SELECT ... FOR UPDATE`; `PESSIMISTIC_READ` -> shared lock (dialect dependent).
- Always set a lock timeout; always lock rows in a consistent order to avoid deadlocks; keep the transaction short.
- Work queues: `FOR UPDATE SKIP LOCKED` (via Hibernate's `SKIP_LOCKED` lock option or native SQL) lets several workers claim different rows.
- Lock timeout support varies by database; verify against the target engine.
- Locking a row via a query with `setLockMode(...)` and a fetch join may lock more rows than expected; lock the root only.

## Isolation and anomalies

Hibernate does not change isolation levels. Default `READ COMMITTED` allows non-repeatable reads across queries; the persistence context gives repeatable reads for entities loaded by id within one session. Do not assume a read-then-write check-and-act is safe: use `@Version`, a lock, or a unique constraint (and handle `ConstraintViolationException`).

## Transaction boundaries

- One use case = one transaction at the service/application layer, not in repositories or controllers, and not per entity call.
- Keep the persistence context scope = transaction scope (transaction-scoped `EntityManager`). An `EntityManager` is not thread-safe; never share it, or entities, across threads.
- No HTTP calls, message sends, or long computation inside a transaction: they hold connections and locks. Publish events after commit (outbox pattern for reliability).
- Read-only use cases: mark the transaction read-only (framework facility) or `session.setDefaultReadOnly(true)`; this skips dirty checking snapshots.
- Rollback: JPA does not define rollback-by-exception-type for a resource-local `EntityTransaction`; call `rollback()` explicitly in a `catch`/`finally`. Automatic rollback rules (for example on `RuntimeException` but not checked exceptions) come from the surrounding framework or container, such as Spring `@Transactional` or Jakarta `@Transactional`.
- After a persistence exception the session is in an undefined state: discard it, do not continue using it.
- Flush modes: `AUTO` flushes before queries that touch dirty entity tables; unexpected flushes inside loops show up in logs as updates before selects. Use `FlushModeType.COMMIT` or `em.setFlushMode` sparingly, only when you understand the stale-read risk.
- `merge` returns a managed copy: use the returned instance, not the argument. Prefer loading and modifying a managed entity over `merge` of detached state.
- `save`/`persist` on already-managed entities is unnecessary: dirty checking flushes changes at commit.

## Second-level cache basics

Levels: first-level (persistence context, always on, per session), second-level (per `SessionFactory`, opt-in, shared), query cache (opt-in, result ids).

Enable only for read-mostly data that is expensive to load, and that this application alone writes (or that tolerates staleness):

```properties
hibernate.cache.use_second_level_cache=true
# Requires hibernate-jcache and a JCache provider, e.g. Ehcache, on the classpath.
hibernate.cache.region.factory_class=jcache
```

```java
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
class Country { ... }
```

- `shared-cache-mode` `ENABLE_SELECTIVE` (cache only `@Cacheable`) is the safest.
- Concurrency strategies: `READ_ONLY` (immutable), `NONSTRICT_READ_WRITE` (tolerates staleness), `READ_WRITE`, `TRANSACTIONAL` (JTA).
- Query cache is rarely a win: any write to a queried table invalidates its results. Avoid by default.
- Bulk HQL/JPQL DML executed through Hibernate invalidates the affected second-level and query-cache regions automatically, and native DML run through Hibernate also triggers cache cleanup (possibly all regions when query spaces are unknown). What stays stale is managed entities in the current persistence context: flush before bulk DML, then `clear()` or refresh afterwards. Writes outside Hibernate (other applications, direct JDBC) are not seen; they need a separate invalidation strategy such as `getCache().evict(...)`.
- Multi-node deployments need a distributed or invalidating provider; local-only caches serve stale data per node.
- Measure with statistics (`hibernate.generate_statistics`) before and after; if the hit ratio is low, remove it.
- Cache entities by id (`find`), collections separately (`@Cache` on the collection mapping), and keep cached entities small.
queries-pagination-batching.md 6.8 KB
# Queries, pagination, batching

## Pagination

### Offset pagination

```java
List<Order> orders = em.createQuery("select o from Order o order by o.createdAt desc, o.id desc", Order.class)
    .setFirstResult(page * size)
    .setMaxResults(size)
    .getResultList();
```

- Always include a deterministic `ORDER BY` with a unique tiebreaker (`id`).
- Large offsets are slow (the DB scans and discards rows). Use keyset pagination for deep paging.

### Collection fetch join + pagination (HHH000104)

```java
// anti-pattern
em.createQuery("select o from Order o join fetch o.lines", Order.class)
  .setMaxResults(20).getResultList();
```

Hibernate logs `HHH000104: firstResult/maxResults specified with collection fetch; applying in memory` (Hibernate 6: `HHH90003004`). It loads **every** matching row and paginates in the JVM: memory and latency explode.

Fix (two queries):

```java
List<Long> ids = em.createQuery("select o.id from Order o where exists (select 1 from o.lines) order by o.createdAt desc, o.id desc", Long.class)
    .setMaxResults(20).getResultList();

List<Order> orders = em.createQuery(
    "select distinct o from Order o join fetch o.lines where o.id in :ids order by o.createdAt desc, o.id desc",
    Order.class).setParameter("ids", ids).getResultList();
```

The `exists` filter matches the inner `join fetch`, which drops orders without lines; use `left join fetch` and drop the filter to keep them. Alternatives: fetch only to-one associations in the paged query and rely on `@BatchSize`/`default_batch_fetch_size` for collections; or use a DTO projection. Fetch joins on `@ManyToOne` are safe with pagination.

### Keyset (seek) pagination

```java
List<Order> next = em.createQuery("""
    select o from Order o
    where (o.createdAt < :ts or (o.createdAt = :ts and o.id < :id))
    order by o.createdAt desc, o.id desc
    """, Order.class)
  .setParameter("ts", lastTs).setParameter("id", lastId)
  .setMaxResults(size).getResultList();
```

Needs an index on the sort columns (`created_at desc, id desc`), constant time per page, stable under inserts; no "jump to page N". Return an opaque cursor made from the last row's sort values. Hibernate 6.5+/7 also has `KeyedPage`/`KeyedResultList` APIs on `SelectionQuery`; check the docs of your version.

### Total counts

A separate `count` query per page is costly; skip it when the UI can use "has next" (fetch `size + 1` rows).

## JDBC batching (inserts and updates)

Enable JDBC batching with a positive batch size:

```properties
hibernate.jdbc.batch_size=50
```

Hibernate can batch inserts with sequence, UUID, or assigned identifiers. `IDENTITY` prevents JDBC batching of entity **inserts** because Hibernate must execute each insert to obtain its generated id; it does not prevent batching updates. Do not change an existing identifier strategy solely to enable batching without considering its other tradeoffs.

Optional tuning (measure against the actual database and driver):

```properties
hibernate.order_inserts=true
hibernate.order_updates=true
hibernate.jdbc.batch_versioned_data=true
```

Ordering statements may group compatible operations, and PostgreSQL `reWriteBatchedInserts=true` / MySQL `rewriteBatchedStatements=true` may improve driver throughput; neither ordering nor driver rewrite flags are prerequisites for Hibernate JDBC batching. Check the dialect, driver, and Hibernate version before changing settings.

Write pattern for large loads:

```java
for (int i = 0; i < items.size(); i++) {
    em.persist(items.get(i));
    if ((i + 1) % batchSize == 0) {
        em.flush();
        em.clear();      // release memory and dirty-checking cost
    }
}
```

Keep `batchSize` equal to `hibernate.jdbc.batch_size`. Commit per chunk (own transaction) if partial progress is acceptable.

Entities referenced after `clear()` are detached; reload or use `getReference`.

## Bulk operations and StatelessSession

- Updates over many rows: set-based `update Order o set o.status = :s where ...` (bypasses lifecycle callbacks, `@Version` unless `versioned`, and cascades; Hibernate invalidates the affected second-level cache regions itself, but managed entities in the current persistence context become stale, so flush before and clear or refresh afterwards).
- Pure ETL/import: `StatelessSession` (no persistence context, no dirty checking, no cascade) with `insert`/`update`.
  - Hibernate 6: it bypasses the second-level cache and uses `hibernate.jdbc.batch_size` for JDBC batching.
  - Hibernate 7: it uses the second-level cache by default (disable per session if unwanted), and `hibernate.jdbc.batch_size` has no effect on it; set the batch size with `StatelessSession.setJdbcBatchSize(n)` and prefer the bulk operations `insertMultiple`/`updateMultiple`/`upsertMultiple`/`deleteMultiple`.
  - Confirm the API for your exact version.
- Streaming reads: `query.getResultStream()`/`scroll` with `hibernate.jdbc.fetch_size`; close the stream and clear the context periodically. Many drivers (PostgreSQL) only stream inside a transaction with autocommit off and a fetch size set.

## Query hygiene

- Bind parameters; never concatenate user input into JPQL/native SQL.
- `IN` lists: large lists blow up the SQL cache; Hibernate pads parameters with `hibernate.query.in_clause_parameter_padding=true`, and databases cap parameter counts, so chunk (e.g. 500-1000).
- `hibernate.query.fail_on_pagination_over_collection_fetch=true` only throws when Hibernate would really paginate in memory. Hibernate 7.4+ only (the 7.4 query language guide: "Prior to Hibernate 7.4, limits didn't play well with many-valued fetch joins"; on 7.0-7.3 pagination over a collection fetch join stays in memory on every dialect, so this guard is useful there). Verified in the 7.4 source (`SqmQueryImpl`/`AbstractSqmSelectionQuery`): when the dialect supports `LIMIT`/`OFFSET` in a subquery (`supportsOffsetInSubquery`, true for PostgreSQL, MySQL, H2...), Hibernate 7.4+ pushes the pagination into a derived table, so `join fetch` + `setMaxResults` (and Spring Data `Pageable` on such a query) is paginated by the database and the setting never fires. It fires only for dialects without that support, or when in-memory limiting is forced; the old `HHH000104` warning is then logged otherwise. Do not use it as a guard on 7.4+ with such dialects: check the generated SQL for `limit`/`fetch first`, and still prefer the two-step (ids first, then fetch) pattern for portability.
- `@QueryHints(readOnly)`/`setHint("org.hibernate.readOnly", true)` for read paths that load entities but never modify them.
- Prefer JPQL/HQL or Criteria for portability; use native SQL for database-specific features (window functions, `SKIP LOCKED`, upserts), mapped to DTOs.
- `existsBy`-style checks: `select 1 ... fetch first 1 rows only` / `count(*) > 0` instead of loading entities.
- Check generated SQL for `select *`-like entity loads where only 2 columns are needed: use projections.
tooling-and-versions.md 6.1 KB
# Tooling, diagnosis, migrations, versions

## SQL logging and statistics

Prefer logger categories to `hibernate.show_sql` (which prints to stdout, unformatted, without parameters). Add these elements inside the existing Logback `logback.xml` `<configuration>` (keep its appender and root logger):

```xml
<logger name="org.hibernate.SQL" level="DEBUG"/>
<logger name="org.hibernate.orm.jdbc.bind" level="TRACE"/>
```

`org.hibernate.orm.jdbc.bind` is for Hibernate 6+; on Hibernate 5 use `org.hibernate.type.descriptor.sql.BasicBinder`. For Log4j2, configure the same categories with `<Logger name="..." level="..."/>` elements inside `<Loggers>` in `log4j2.xml`; bare category properties in `hibernate.properties` do not configure either backend.

Statistics and slow-query log:

```properties
hibernate.generate_statistics=true
hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=25
```

For total SQL statement-count assertions in N+1 regression tests, compare `sessionFactory.getStatistics().getPrepareStatementCount()` before and after the use case, or use a datasource proxy (e.g. datasource-proxy, p6spy). `getQueryExecutionCount()` counts executed ORM queries, not secondary SELECTs issued to initialize lazy associations; `getEntityFetchCount()` and `getCollectionFetchCount()` are useful supplemental diagnostics, not total statement counts. Keep logging at DEBUG/TRACE only in dev/test; statistics have overhead.

Use `EXPLAIN (ANALYZE)` on the real database for slow SQL; indexes on foreign keys are your responsibility (Hibernate does not create them for FKs on most databases).

## Testing persistence code

- Test against the production database engine via Testcontainers (`java-testcontainers`), not H2 with a compatibility mode.
- Flush and clear in tests (`em.flush(); em.clear();`) before asserting reads, otherwise you only test the first-level cache.
- Run the real migrations in tests, and use `hibernate.hbm2ddl.auto=validate` to catch mapping/schema drift.
- Add a statement-count assertion for list endpoints to prevent N+1 regressions.

## Connection pool sizing

- Hibernate uses the pool for each transaction; pool size bounds concurrent DB work, not request count. Start small (roughly `cores * 2 + effective spindles` rule of thumb, typically 10-20 per application instance) and tune with measurements.
- Total connections across instances must stay below the database `max_connections`.
- Long transactions, OSIV, and remote calls in transactions are the usual cause of pool exhaustion, not too few connections.
- Set connection timeout, max lifetime (below DB/proxy idle limits), and leak detection (HikariCP `leakDetectionThreshold`) in dev.
- Use the pool's `autoCommit=false` and `hibernate.connection.provider_disables_autocommit=true` to delay connection acquisition until the first statement, when your pool supports it.

## Schema management

- Production: Flyway or Liquibase migrations, versioned and reviewed; `hibernate.hbm2ddl.auto` set to `validate` or `none`.
- `update`/`create`/`create-drop` only for prototypes and throwaway tests; `update` never drops or renames and can silently diverge from environments.
- Jakarta Persistence schema generation (`jakarta.persistence.schema-generation.*`) can emit a script to diff against; do not apply it blindly.
- Keep migrations compatible with the old release for zero-downtime (expand/contract). Sequence `INCREMENT BY` must match `allocationSize`.
- Name constraints and indexes explicitly in migrations; add indexes on foreign keys and on filter/sort columns.

## Hibernate version differences (detect first)

| Topic | Hibernate 5.x | Hibernate 6.x | Hibernate 7.x |
| --- | --- | --- | --- |
| Namespace | `javax.persistence` (5.5+ also offers `hibernate-core-jakarta`) | `jakarta.persistence` | `jakarta.persistence` |
| Jakarta Persistence | 2.2 | 3.0 (6.0-6.1), 3.1 (6.2+) | 3.2 |
| Java baseline | 8+ | 11+ | 17+ |
| Query engine | HQL parser (ANTLR 2) | Rewritten (semantic query model, ANTLR 4); stricter HQL; more SQL features | Continues 6 architecture; more HQL features, stricter validation |
| Fetch-join duplicates | Need `DISTINCT` | Auto de-duplicated | Same as 6 |
| Pagination + collection fetch warning | `HHH000104` | `HHH90003004` | Same as 6 |
| Id generation | Legacy `hibernate.id.new_generator_mappings` | Sequence-first `AUTO`; `@GenericGenerator` deprecated from 6.5 | Prefer standard annotations and `@UuidGenerator`/`@IdGeneratorType` |
| Metamodel generator | `hibernate-jpamodelgen` | `hibernate-jpamodelgen` (`hibernate-processor` is the successor, introduced in 7.0) | `hibernate-processor` |
| Hibernate Reactive/other | n/a | Separate artifacts | Separate artifacts |

Migration notes (5 -> 6): fix `javax` -> `jakarta` imports (`javax-to-jakarta-migration` skill), review HQL for stricter parsing, re-check generated sequence names and `allocationSize`, re-check `@Type`/custom type usages and `AttributeConverter`s, `Query.getResultList` behavior and `@Where`/`@Filter` use. Read the official migration guides: <https://docs.hibernate.org/orm/6.0/migration-guide/> and the matching guide for 7. Hibernate 8 is in beta at the time of writing; do not assume its APIs.

Version-specific APIs mentioned elsewhere in this skill (entity-graph hint vs `setEntityGraph`, `KeyedPage`, UUID styles) should be checked against the project's Hibernate version before use.

## Tools

- Metamodel/typed Criteria: `hibernate-jpamodelgen` for Hibernate 6.x (`hibernate-processor` first appears in 7.0.0.Alpha1 on Maven Central), `hibernate-processor` for Hibernate 7 (`org.hibernate.orm:hibernate-processor`, `provided`/annotation-processor scope; `hibernate-jpamodelgen` 7.x is only a Maven relocation to it).
- JDK 23+ no longer runs annotation processors found only on the classpath: with a plain `provided` dependency `Entity_` classes are not generated. Set `<proc>full</proc>` on `maven-compiler-plugin` (or list the processor in `annotationProcessorPaths`; Gradle: `annotationProcessor`).
- Bytecode enhancement (lazy basic attributes, dirty tracking, lazy to-one inverse): Hibernate Maven/Gradle plugin; test carefully.
- Validation: Jakarta Bean Validation integrates with persist/update and does not replace DB constraints.

License (MIT)

View full license text
MIT License

Copyright GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.