BootUI
Try it
Setup
Features
Workshop
Properties
AI agents
Ecosystem
GitHub
Try it
Setup
Features
Workshop
Properties
AI agents
Ecosystem
GitHub
    • Try the sample app
    • Setup
    • Spring WebFlux
    • Quarkus
    • CI/CD and GitHub Actions
    • Java agent
    • Activation and safety
    • Non-standard runtimes
    • Troubleshooting
    • All features
    • Scorecard
    • Live Activity
    • Runtime Insights
    • Advisors
    • Runtime
    • Configuration
    • Database
    • Security
    • Services
    • Diagnostics
    • Java Agent
    • Developer tools
    • Workshop overview
    • 00 - Runtime understanding
    • 01 - Setup and tooling
    • 02 - Configuration and wiring
    • 03 - Runtime journal
    • 04 - Runtime Insights
    • 05 - Java instrumentation
    • 06 - Assessment and impact
    • 07 - Agent change loop
    • 08 - Going further
    • Participant worksheet
    • A - Prompts
    • B - Troubleshooting
    • C - Frameworks
    • D - Extensions
    • Properties
    • Framework support
    • AI agents
    • Command line
    • Framework-managed CI tests
    • CI reference
    • BootUI family
    • Known limitations
    • Architecture
    • REST API
    • Spring
    • Hibernate
    • Database
    • Security
    • Vulnerabilities
    • Memory
    • Pentesting
    • GraalVM readiness
    • CRaC readiness
    • Quarkus
    • Quarkus security
    • Repository
    • Specification
    • Roadmap
    • 2.0 design record
    • Try 2.0 early
    • v2 validation report
    • Releasing 2.0
    • Quarkus design notes
    • WebFlux design notes
  • Privacy

Hibernate checks

The Hibernate panel runs a fixed, on-demand ruleset against your application's mapped JPA entities. It reads the JPA EntityManagerFactory metamodel, selected persistence-unit observations, and verified Spring Data JPA repository metadata where available. It never intercepts runtime queries, invokes repositories, executes SQL, or modifies mappings.

The checks are heuristic review prompts. They highlight common Hibernate and JPA performance and maintainability risks, but the right remediation still depends on your query patterns and data model.

Reading more than the preview

The ten-entry sampleViolations preview does not cap violationCount. View violations, or GET <api>/hibernate/rules/{id}/violations?scanId=...&offset=0&limit=100, retrieves the retained sequence, including persistence-unit labels, without re-reading entities or executing SQL. Retention is bounded across rules and units, so check truncated separately from evidence coverage. See snapshot, retention, and MCP/CLI retrieval.

Availability and bounds

The panel is available when Hibernate ORM and an EntityManagerFactory bean are present. If either is missing, or the metamodel cannot be read, BootUI returns a stable empty report with an explanatory status.

The scan covers the mapped entities your JPA metamodel reports, which includes entities added through @EntityScan or custom persistence-unit configuration, without scanning the whole classpath. Non-identifier @Embedded (@Embeddable) attributes are expanded recursively (up to a bounded depth, respecting @AttributeOverride and @Convert overrides) so mappings inside embedded value objects are inspected alongside direct entity attributes. Entities Hibernate Envers adds itself, such as DefaultRevisionEntity, are left out because the application cannot edit them (an application-declared revision entity is still scanned); Envers' generated *_AUD entities are map-based and never reach the metamodel. An entity mapped only in .hbm.xml is discovered, but its XML mapping is not read, so rules that look for missing annotations may report columns the XML configures.

The active catalog contains 80 rules. Twelve retired identifiers stay documented below so old links and persisted dismissals keep their meaning. Retired identifiers are never reused.

Evidence and incomplete scans

Factory settings belong to their persistence unit, not to whichever factory was discovered first. The advisor reads an allowlisted snapshot of effective Hibernate factory options where available and attributes findings to that unit. Effective values come from the factory's own SessionFactoryOptions, SQL statement logger, and selected factory properties. An unset option can be an observed default (for example hibernate.use_sql_comments=false or a slow-query threshold of 0); failed reads and unrecognized values are not treated as defaults.

Factory defaults do not establish per-session overrides, query-cache opt-in, entity-cache eligibility, or workload, and missing or unreadable evidence is not an observed false, zero, or framework default. Missing persistence-unit evidence qualifies usable known-findings scores without discarding findings from other units. See the shared score eligibility policy.

Repository checks need JPA provenance and unambiguous unit and domain attribution. Native queries, composed query annotations, projections, and entity graphs all affect applicability. Unsupported and ambiguous query shapes are not guessed, and Panache query methods stay outside the repository analysis.

The collection JOIN FETCH checks (HIB-FETCH-003 and HIB-QUERY-007) exclude verified static, single-root SELECTs that contain no fetch operation, including constructor DTO queries with entity joins. This is rule-specific: other query checks still require their own readable shape. Unverified, named, rewritten, dynamic, malformed, multi-root, and unsupported fetch queries retain their coverage limits. Standard inherited JpaRepository save methods remain standard newness evidence even when Java generates a covariant saveAll bridge; actual default overrides, custom save implementations, and unverified entity information remain unknown.

Rule failures and unavailable required evidence produce an incomplete PARTIAL scan while retaining valid findings. The report's results list still contains findings only; the scan message summarizes coverage counts, and the report's diagnostics array lists every affected evaluation as {source, unit, level, message}: source is the rule id (or discovery for an unavailable factory, metamodel, repository metadata or unit attribution), unit is the persistence-unit label (application for application-wide rules), and level is ERROR for a failed rule, WARNING for unavailable evidence, or INFO when the only missing evidence is something this advisor does not observe by design (such as pool auto-commit guarantees). The message says whether the rule reached no conclusion, was partly evaluated with no findings, or reported findings from the evaluated part only, and names the missing evidence kinds with occurrence counts and up to three sanitized examples such as OrderRepository#findRecent or an entity name (for example query provenance, a JPQL shape outside the readable subset, or an unavailable unit setting). Messages use controlled phrases only and never carry query text, property values or exception messages. A failed evaluation is counted as failed, not also as unavailable evidence, and the skipped count excludes both. The array holds at most 200 entries: when more are produced, the last entry has source diagnostics and states how many were omitted, every rule and every distinct discovery reason keeps at least one entry (an ERROR when it has one), remaining slots go to further ERRORs and then round-robin by rule, and scan.message states "Diagnostics show M of N entries" while keeping the full counts. HIB-CONFIG-008 and HIB-CONFIG-021 gaps for a unit whose connection pool cannot be attributed are reported at INFO level because they are advisor limits; they still make the scan PARTIAL (see below). A rule that reports findings but could not evaluate every unit or query carries a coverageNote on its results entry (for example Incomplete in [default]: …) naming up to ten affected units and why, including units where the rule failed. Platform inapplicability is distinct from a failed applicable check, and rulesEvaluated counts distinct active rule attempts, not successful verification of every mapping.

The pool auto-commit default (HIB-CONFIG-008 and HIB-CONFIG-021) is only partly observable: it is read only when a persistence unit can be attributed to a HikariCP or Agroal pool. Where it applies, it and unsupported query-plan evidence can make an ordinary scan PARTIAL even when entity discovery succeeded. That is coverage disclosure, not a claim that the application is broken.

The declaration-based mapping checks are not a complete runtime mapping interpreter. XML overrides, auto-apply converters, custom generators, physical naming, runtime query changes, and some collection classifications cannot be reconstructed from annotations alone. The per-rule limitations below matter when you interpret both a finding and an absence of findings.

Violation locations

A finding about one entity, mapped attribute, or repository method carries a violation location: the entity class, the Java field or getter behind the attribute on its declaring class (a @MappedSuperclass included), or the repository interface method. The JPA metamodel and reflection record no line numbers, so these locations stay at MEMBER or CLASS precision and never show a line. During the explicit scan BootUI reads each located class's recorded source file name from its class file, without loading any class, and resolves its local source path through the Architecture advisor's module and source-set lookup. The class file is found through the class's own class loader. Quarkus serves bytecode-enhanced entities from memory, in dev and test mode alike, so BootUI then asks the same loader for every root of the entity's package and keeps the one local output directory that holds its class file. It keeps no path when no root or more than one root holds it, when an archive root holds a copy, when a root cannot be read, or when the package has more than 64 roots. At most 1,024 located classes are read per scan. Configuration, settings, and profile findings, and findings that span several elements such as composite identifier classes, carry no location. Unit-labelled samples and retained details keep the same location for the same finding across persistence units.

Finding identity

Every finding has a canonical identity, used to compare a scan with the previous one (Changes since the previous scan). It is v1: followed by percent-encoded parts joined with |, and it never contains a value, SQL text or a message:

Finding aboutIdentity parts
A mapped attributeunit=<unit>, entity=<concrete entity class>, member=<attribute>
An entityunit=<unit>, entity=<entity class>
A repository query methodunit=<unit>, repository=<interface>, method=<name>(<parameter types>)
A settingunit=<unit>, setting=<property>

A rule can add a part when one element has several findings (path= for each paged JOIN FETCH path of HIB-FETCH-003). HIB-ID-007 is keyed on unit=<unit> and idclass=<class> alone, since several entities can share one identifier class. An inherited attribute is keyed on the concrete entity, so two entities that inherit it have two identities, and overloaded repository methods stay apart. A finding without a persistence unit uses unit=application. The unit is its label, which is the persistence unit name where the framework reports one and a positional unit-N otherwise, so a positional label can shift when a factory fails to start. The same identity is what a single-finding dismissal is matched on.

Version baseline

The audited baselines are Spring Boot 4.1.1 with Hibernate 7.4.5.Final, and Quarkus 3.33.3.1 with Hibernate 7.2.19.Final, both on Jakarta Persistence 3.2.0. BootUI now builds its Quarkus adapter against Quarkus 3.40.2, which manages Hibernate 7.4.17.Final. Your application may override these versions, and version-dependent conclusions use runtime evidence. Primary references and version caveats are listed at the end of this catalog.

Severity scale

SeverityMeaning
CRITICALA configuration choice that can immediately damage production data. Currently emitted only by HIB-CONFIG-002, for destructive schema actions under a production-like profile.
HIGHA mapping or configuration choice that commonly causes large performance surprises, or that breaks transactional atomicity (HIB-CONFIG-021).
MEDIUMA mapping or configuration issue that usually warrants review before production use.
LOWLower-impact hygiene findings.
INFOAn informational prompt where the fix depends heavily on project context.

Quarkus and Jakarta create is create-only, unlike Hibernate hbm2ddl.auto=create.

The results panel lists only checks that found something, ordered by severity, finding count, and rule id. Each rule includes a few sample mapped members plus a remediation link.

After a single-finding dismissal, a fully retained rule uses the highest grade of its remaining persistence-unit evaluations. Missing retained details or active grade evidence preserve the original grade conservatively; dismissal never completes unknown coverage.

The advisor score applies the shared severity penalty to every concrete finding, not once per violated rule. Dismissing a rule removes all of its findings from the score.


Filter the list, then jump to a check — the detail below narrows to match.

  1. HIB-FETCH-001MEDIUMReview eager to-one fetch plans
  2. HIB-FETCH-010HIGHEager collection fetching should stay bounded
  3. HIB-FETCH-003HIGHCollection fetch joins should not be paged directly
  4. HIB-FETCH-002INFOBatch fetching should cover lazy secondary-select associations
  5. HIB-FETCH-005LOWEnhanced @Lob attributes should be loaded lazily
  6. HIB-FETCH-006MEDIUMCollection associations should not declare @Fetch(JOIN)
  7. HIB-FETCH-007MEDIUMLazy basic attributes require bytecode enhancement
  8. HIB-FETCH-008INFOSubselect collection fetching should be reviewed
  9. HIB-FETCH-009LOWMultiple lazy @Lob attributes should use distinct @LazyGroup names
  10. HIB-ID-001MEDIUMReview IDENTITY insert-generation trade-offs
  11. HIB-ID-002MEDIUMReview table-based identifier allocation
  12. HIB-ID-003MEDIUMReview sequence allocation declarations
  13. HIB-ID-004INFOReview provider-selected identifier strategies
  14. HIB-ID-005LOWReview generated UUID strategy when index locality matters
  15. HIB-ID-006HIGHGenerationType.IDENTITY disables JDBC batch inserts
  16. HIB-ID-007HIGHComposite identifier classes must satisfy the JPA contract
  17. HIB-MAP-001MEDIUMOne-to-many associations should be bidirectional or join-column based
  18. HIB-MAP-002MEDIUMReview many-to-many list semantics
  19. HIB-MAP-003MEDIUMEnum attributes should declare an explicit storage strategy
  20. HIB-MAP-004HIGHMany-to-many associations should not cascade remove
  21. HIB-MAP-005HIGHMany-to-one associations should not cascade remove
  22. HIB-MAP-006MEDIUMOne-to-one associations should prefer shared primary keys
  23. HIB-MAP-007INFOReview TABLE_PER_CLASS polymorphic queries
  24. HIB-MAP-008MEDIUM@NotFound(IGNORE) should be reviewed
  25. HIB-MAP-009MEDIUMPersistent attributes should not be Optional
  26. HIB-MAP-010MEDIUMReview element-collection list ordering and mutation cost
  27. HIB-MAP-011INFOEntity classes should not be final
  28. HIB-MAP-013INFOString columns should declare explicit length
  29. HIB-MAP-014LOWBigDecimal columns should declare precision and scale
  30. HIB-MAP-015LOWDate/time attributes should use java.time
  31. HIB-MAP-016LOW@ManyToOne should set optional=false when the join column is non-nullable
  32. HIB-MAP-018MEDIUMReview lazy inverse @OneToOne without enhancement
  33. HIB-MAP-020MEDIUMReview writable unidirectional one-to-many join-column DML
  34. HIB-MAP-022INFOExplicit ordinal enum mappings should be reviewed
  35. HIB-MAP-023MEDIUMSet element collections of embeddables need equals and hashCode
  36. HIB-MAP-024LOW@Lob on PostgreSQL stores values as large objects
  37. HIB-MAP-025HIGHJPA mapping annotations should match the class access type
  38. HIB-MAP-027LOWDeprecated @GenericGenerator should be replaced
  39. HIB-MAP-028LOWDeprecated @Cascade annotation should be replaced
  40. HIB-ENTITY-001INFOEntities should override equals and hashCode consistently
  41. HIB-ENTITY-005LOWPersistent fields should not be public
  42. HIB-ENTITY-006INFOReview primitive-version newness semantics
  43. HIB-ENTITY-007MEDIUMReview assigned-ID Spring Data newness
  44. HIB-ENTITY-008INFOMutable entities should declare @Version for optimistic locking
  45. HIB-ENTITY-009INFOUnique business-key columns should consider @NaturalId
  46. HIB-ENTITY-010INFOPrefer a numeric @Version over a timestamp
  47. HIB-ENTITY-011HIGHKotlin entities should not be declared as data class
  48. HIB-ENTITY-012HIGHPanacheEntity subclasses should not shadow id or declare custom identifiers
  49. HIB-QUERY-001INFO@Modifying bulk queries should clear stale persistence context
  50. HIB-QUERY-002INFOReview streaming query resource lifetime
  51. HIB-QUERY-003INFONative Page queries should review count derivation
  52. HIB-QUERY-004MEDIUMDerived deleteBy methods load entities before deletion
  53. HIB-QUERY-005INFOEager to-one associations should be JOIN FETCHed in entity-returning queries
  54. HIB-QUERY-007MEDIUMQueries should not JOIN FETCH more than one collection
  55. HIB-QUERY-008MEDIUMBulk updates leave @Version unchanged
  56. HIB-QUERY-009MEDIUMSpring Data interface projections should avoid @Value SpEL
  57. HIB-QUERY-010MEDIUMReview filtered collection fetch joins
  58. HIB-CONFIG-003HIGHLazy loading outside transactions should stay disabled
  59. HIB-CONFIG-004INFOJDBC batching should be configured for writes
  60. HIB-CONFIG-005INFOJDBC batching should order inserts and updates
  61. HIB-CONFIG-006INFOSlow query logging should be available in development
  62. HIB-CONFIG-008INFOConnection providers should disable auto-commit explicitly
  63. HIB-CONFIG-009INFOCollection-parameter queries should use IN-clause padding
  64. HIB-CONFIG-010HIGHQuery caching requires effective region support
  65. HIB-CONFIG-002INFOSchema generation should not mutate non-test databases
  66. HIB-CONFIG-012MEDIUMSQL logging should be off when a production profile is active
  67. HIB-CONFIG-013LOWReview applicable JDBC temporal binding
  68. HIB-CONFIG-014HIGHHibernate's built-in connection pool should not be used
  69. HIB-CONFIG-015INFODeferred script initialization should have an intentional order
  70. HIB-CONFIG-016INFOFail on pagination over collection fetch
  71. HIB-CONFIG-017LOWDisable SQL formatting in production
  72. HIB-CONFIG-018HIGHJDBC value logging should be off in production
  73. HIB-CONFIG-019INFOSQL comments should be enabled intentionally
  74. HIB-CONFIG-020INFOOracle JDBC fetch size should exceed the driver default
  75. HIB-CONFIG-021HIGHProvider auto-commit setting should match the pool
  76. HIB-CONFIG-022INFOUnnecessary explicit standard hibernate.dialect configuration
  77. HIB-CACHE-001INFOCached entity association coverage should be reviewed
  78. HIB-CACHE-002MEDIUMREAD_ONLY cache strategy on writable entities is unsafe
  79. HIB-CACHE-003INFOImmutable cached entities should use READ_ONLY
  80. HIB-CACHE-004MEDIUM@NaturalIdCache entities should also enable entity second-level caching

Fetching

HIB-FETCH-001 - Review eager to-one fetch plans

  • Severity: MEDIUM
  • Inspects: mapped @ManyToOne and @OneToOne attributes.
  • Fires when: the declaration is FetchType.EAGER, explicitly or through JPA's ordinary to-one default.
  • Why it matters: eager to-one declarations deserve a use-case review, but do not by themselves establish unbounded loading, extra SELECTs, or N+1 queries. The actual fetch plan and workload determine the cost.
  • Recommendation: review whether each use case needs the association. Consider LAZY with explicit fetch joins, entity graphs, or DTO queries, and verify the actual query plan.
  • Ownership: eager collections belong to HIB-FETCH-010 at HIGH, not to this rule. An unreadable fetch declaration (including an XML-only mapping) is incomplete evidence, not a confirmed lazy mapping or a complete pass.
  • Persistence 4: FetchType.DEFAULT is resolved from that persistence unit's observed bootstrap defaults, not assumed to mean EAGER. Quarkus 4 records the completed Hibernate mapping default without opening a session or executing SQL. Missing defaults leave this check incomplete while preserving explicit EAGER findings. A graph-free @jakarta.persistence.Fetch(type = ...) overrides the association's fetch declaration, including when stored in its repeatable container. Named-graph and subgraph options do not redefine the ordinary declaration.

Eager-fetch dismissal migration

HIB-FETCH-001 now covers to-one mappings only. Existing rule and single-finding dismissals remain attached to HIB-FETCH-001 and are not copied to HIB-FETCH-010. Previously hidden eager collection findings therefore reappear at HIGH on the next explicit scan. Review and dismiss them under HIB-FETCH-010 separately if appropriate.

A to-one-only HIB-FETCH-001 finding no longer trips a HIGH threshold. Unreadable fetch declarations leave coverage incomplete: under the default Action policy, Hibernate is then SKIPPED (EVIDENCE_UNEVALUABLE), so even retained HIGH findings do not gate. A required Hibernate assessment instead returns NOT_ASSESSED. Severity weights are unchanged; XML configuration alone is not a CI failure. See the CI policy reference.

HIB-FETCH-010 - Eager collection fetching should stay bounded

  • Severity: HIGH
  • Inspects: mapped @OneToMany, @ManyToMany, and @ElementCollection attributes.
  • Fires when: the collection declaration opts into FetchType.EAGER.
  • Why it matters: loading all collection members can amplify the fetched graph and payload even when the caller does not need them. This is a mapping-risk prompt, not a measured query-count claim.
  • Recommendation: prefer LAZY collections and load needed members with targeted queries, fetch joins, entity graphs, or DTO queries. Bound loading to the use case; do not directly page collection fetch joins.
  • Evidence: collection ownership uses relationship metadata, including map-valued element collections, not a Java return-type guess. Unreadable fetch declarations remain incomplete; known findings and their counts are retained. On Hibernate 8, graph-free Jakarta @Fetch overrides are included, and collection FetchType.DEFAULT resolves to LAZY, independently of the unit's to-one default.

HIB-FETCH-003 - Collection fetch joins should not be paged directly

  • Severity: HIGH
  • Inspects: Spring Data JPA @Query methods with a Pageable parameter and resolvable JPQL JOIN FETCH paths.
  • Fires when: an attributable, supported paged JPA query fetch-joins a mapped collection and the known runtime or declared query hint establishes an in-memory pagination risk. An unknown runtime is not treated as an older version.
  • Why it matters (Hibernate < 7.4): collection fetch joins duplicate root rows, and versions before 7.4 applied the Pageable limit in memory after loading the full, duplicated result set instead of at the SQL level.
  • Recommendation: page root identifiers first, then fetch the required collection graph in a second query inside the same transaction.
  • Ownership: this rule alone reports the affected queries. HIB-CONFIG-016 reviews the unit-wide fail-fast guard once, without repeating these findings.
  • Hibernate 7.4+: the "Limits and fetch joins" migration-guide entry documents that the limit for a paged query with a collection JOIN FETCH is now applied in the generated SQL itself; the org.hibernate.limitInMemory query hint restores the pre-7.4 in-memory behavior. The check does not certify SQL pushdown merely from the version: dialect/query-plan fallback remains possible, and an explicit true hint can bypass the ordinary pagination guard. Unknown query/runtime evidence is reported as a coverage gap, not a blanket warning or proof of safety.

HIB-FETCH-004 - Review entities with multiple bag collections

Retired. Multiple lazy bag declarations are valid; their existence does not establish simultaneous fetching. HIB-QUERY-007 reviews supported query shapes instead. A Java List without @OrderColumn does not itself prove effective BAG semantics because Hibernate can supply an implicit list index. Changing collections to sets also does not eliminate Cartesian multiplication when multiple collections are fetched together.

HIB-FETCH-002 - Batch fetching should cover lazy secondary-select associations

  • Severity: INFO
  • Inspects: lazy to-one and collection mappings, the owning factory's default batch-fetch size, association-level @org.hibernate.annotations.BatchSize, and target-entity @BatchSize for lazy to-one associations.
  • Fires when: a lazy association can initialize through secondary selects and no global or applicable local batch fetch size is detected.
  • Why it matters: lazy associations without batch fetching can produce N+1 select patterns when the same association is traversed across multiple owner rows.
  • Recommendation: set a bounded global batch-fetch size or targeted @BatchSize for associations traversed across multiple owners; use explicit fetch plans or paged/filtered queries for a single oversized collection.
  • Quarkus: effective factory options include Quarkus's integration default even when quarkus.hibernate-orm.fetch.batch-size is absent from raw configuration. Named units are inspected separately.

HIB-FETCH-005 - Enhanced @Lob attributes should be loaded lazily

  • Severity: LOW
  • Inspects: persistent attributes annotated with @Lob on bytecode-enhanced entities.
  • Fires when: enhancement is available and a materialized @Lob attribute (for example String or byte[]) does not declare @Basic(fetch = FetchType.LAZY). java.sql.Blob, Clob, and NClob attributes are JDBC locators that are not materialized when the row is hydrated, so they are not reported. On a PostgreSQL unit, an attribute that HIB-MAP-024 reports is left to that rule, which recommends removing @Lob instead.
  • Why it matters: infrequently used materialized CLOB/BLOB values can increase hydration cost. The benefit depends on payload size and access pattern, so this is an optimization prompt rather than a mapping defect.
  • Recommendation: on enhanced entities, annotate infrequently accessed @Lob fields with @Basic(fetch = FetchType.LAZY).
  • Enhancement requirement: Hibernate ORM 7 requires bytecode enhancement to honor lazy basic attributes. This rule deliberately does not recommend @Basic(fetch = LAZY) when enhancement is unavailable; HIB-FETCH-007 instead reports existing ineffective lazy-basic declarations. The advisor relies on transformed-class evidence or an adapter-verified platform capability; an ordinary Hibernate enhancement setting alone does not prove that application classes were transformed. Quarkus provides that verified capability at build time.

HIB-FETCH-006 - Collection associations should not declare @Fetch(JOIN)

  • Severity: MEDIUM
  • Inspects: collection associations annotated with Hibernate's @Fetch.
  • Fires when: a @OneToMany or @ManyToMany declares @Fetch(FetchMode.JOIN).
  • Why it matters: mapping-level joins can load more collection state than a use case needs. They do not force every JPQL query to join: query fetching directives determine that path. The declaration does not prove an actual Cartesian product or pagination failure.
  • Recommendation: prefer @Fetch(FetchMode.SELECT), an explicit entity query, or a DTO projection, and request JOIN FETCH only in the specific queries that need the graph.

HIB-FETCH-007 - Lazy basic attributes require bytecode enhancement

  • Severity: MEDIUM
  • Inspects: attributes declaring @Basic(fetch = FetchType.LAZY) and the owning entity's enhancement state.
  • Fires when: a lazy basic attribute belongs to an entity whose relevant enhancement is known to be absent. Unavailable enhancement evidence is not treated as verified absence.
  • Why it matters: without enhancement, Hibernate cannot intercept access to a basic field and the requested lazy column loading is ineffective.
  • Recommendation: enable Hibernate bytecode enhancement, or remove the misleading LAZY declaration.

HIB-FETCH-008 - Subselect collection fetching should be reviewed

  • Severity: INFO
  • Inspects: collection associations declaring @Fetch(FetchMode.SUBSELECT).
  • Fires when: a mapped @OneToMany or @ManyToMany uses subselect fetching.
  • Why it matters: initialization can load the same collection role for the originating registered query/load group, not necessarily every owner in the persistence context. A large owner group can fetch more data than the caller needs.
  • Recommendation: keep SUBSELECT only for bounded owner sets. Prefer an explicit entity query or DTO projection when owner or collection cardinality can be large.

HIB-FETCH-009 - Multiple lazy @Lob attributes should use distinct @LazyGroup names

  • Severity: LOW
  • Inspects: materialized @Lob @Basic(fetch = FetchType.LAZY) attributes (excluding JDBC Blob/Clob locators) and their @org.hibernate.annotations.LazyGroup declarations on bytecode-enhanced entities.
  • Fires when: a bytecode-enhanced entity declares two or more lazy @Lob attributes in the same @LazyGroup (including the default "DEFAULT" group when @LazyGroup is omitted).
  • Why it matters: Hibernate initializes all attributes in the same bytecode-enhancement lazy group together, so reading one lazy @Lob loads the others in the same group in a single SELECT.
  • Recommendation: assign distinct @LazyGroup names to independent lazy @Lob attributes so accessing one large payload does not materialize the others.

Identifiers

HIB-ID-001 - Review IDENTITY insert-generation trade-offs

  • Severity: MEDIUM
  • Inspects: mapped attributes annotated with @GeneratedValue and the persistence unit dialect's sequence support (Dialect#getSequenceSupport().supportsSequences()).
  • Fires when: the generator strategy is GenerationType.IDENTITY and the dialect supports sequences (for example PostgreSQL, Oracle, H2, or MariaDB 10.3+). Skipped as not applicable when the dialect does not support sequences (such as Oracle MySQL, where IDENTITY / AUTO_INCREMENT is native). When dialect sequence support cannot be observed, the rule skips with a missing factory-setting diagnostic rather than guessing.
  • Why it matters: identity columns require the insert to execute immediately so Hibernate can read the generated key, which disables JDBC batch inserts for those entities.
  • Recommendation: prefer SEQUENCE with an allocation size and Hibernate pooled optimizer when the database supports sequences and insert throughput justifies it. IDENTITY is a supported choice, not a mapping defect. When HIB-ID-006 provides the stronger batching-specific finding, this generic advice is not counted again.

HIB-ID-002 - Review table-based identifier allocation

  • Severity: MEDIUM
  • Inspects: mapped attributes annotated with @GeneratedValue.
  • Fires when: the generator strategy is GenerationType.TABLE.
  • Why it matters: table generators emulate sequences through row updates, which can serialize identifier allocation under concurrent inserts.
  • Recommendation: compare generator and pooling choices against the database and insert workload. The declaration does not demonstrate contention, and pooled table allocation may be intentional.

HIB-ID-003 - Review sequence allocation declarations

  • Severity: MEDIUM
  • Inspects: field-level and class-level @SequenceGenerator declarations.
  • Fires when: allocationSize=1.
  • Why it matters: when this declaration selects the active generator, an allocation size of 1 cannot pool sequence values. An unused or overridden declaration does not establish runtime allocation behavior.
  • Recommendation: measure allocation overhead before increasing the size; coordinate the optimizer, database sequence increment and other writers. The advisor does not resolve every named, package-level or custom generator.

HIB-ID-004 - Review provider-selected identifier strategies

  • Severity: INFO
  • Inspects: identifier attributes annotated with @GeneratedValue, excluding UUID-typed identifiers.
  • Fires when: strategy is omitted (or set to AUTO).
  • Why it matters: AUTO deliberately delegates generator selection to the provider. Hibernate normally uses sequence-style generation for numeric identifiers, with a table fallback where sequences are unavailable, but named/custom generators can affect resolution. Explicit AUTO is legal and is not equivalent to IDENTITY.
  • Recommendation: review the selected generator when portability or allocation throughput matters. Retain AUTO when its behavior fits the application; choosing an explicit strategy is not universally required.
  • UUID identifiers: skipped entirely - for a UUID-typed identifier, Hibernate 6 interprets AUTO as the UuidGenerator, not a sequence, so this rule's "sequence-or-table fallback" rationale does not apply. HIB-ID-005 owns the UUID case exclusively, so a UUID @Id @GeneratedValue with no explicit strategy is flagged only once, by HIB-ID-005, with UUID-specific guidance instead of a misleading sequence/table warning.
  • Quarkus/Panache: skipped for the id field inherited as-is from Panache's own PanacheEntity (ORM or Reactive), which declares @Id @GeneratedValue public Long id; with no explicit strategy and cannot be annotated by the application. A custom identifier the application declares itself (including on a PanacheEntityBase subclass) is still checked normally.

HIB-ID-005 - Review generated UUID strategy when index locality matters

  • Severity: LOW
  • Inspects: UUID identifier attributes annotated with @GeneratedValue or @UuidGenerator.
  • Fires when: the attribute uses @GeneratedValue (without a custom/named generator) and omits @UuidGenerator, or declares @UuidGenerator with a non-monotonic style (AUTO, RANDOM, or TIME). Monotonic styles (VERSION_7 and VERSION_6) pass.
  • Why it matters: default random UUID generation can affect index locality, depending on the database and workload. This declaration-level check does not establish an effective custom generator or measured index fragmentation.
  • Recommendation (Hibernate 7.0+): annotate the identifier with @UuidGenerator(style = VERSION_7) (VERSION_6 is also acceptable). Both styles are monotonic, index-friendly UUID variants and only exist starting in Hibernate 7.0 (both @Incubating) - confirmed by diffing UuidGenerator.java between the 6.6 branch (only AUTO/RANDOM/TIME) and the 7.0 branch (adds VERSION_6/VERSION_7).
  • TIME caveat: style = TIME produces an RFC 4122 version 1 UUID (per @UuidGenerator's own Javadoc: "time-based generation strategy consistent with RFC 4122 version 1, but with IP address instead of MAC address"), which places the fast-changing time_low field first and is not materially more index-friendly than a random (v4) UUID - it does not yield the monotonic ordering that makes VERSION_6/VERSION_7 genuinely index-friendly, so do not treat TIME as a fix.
  • Generator caveat: @UuidGenerator without a style defaults to AUTO/RANDOM and is flagged accordingly. String-based, named and custom @IdGeneratorType generators are exempted rather than guessed.
  • Version handling: the check does not read the runtime Hibernate version; every supported runtime uses ORM 7, where VERSION_6/VERSION_7 are available.

HIB-ID-006 - GenerationType.IDENTITY disables JDBC batch inserts

  • Severity: HIGH
  • Inspects: the owning factory's effective JDBC batch size, dialect sequence support (Dialect#getSequenceSupport().supportsSequences()), and identifier attributes annotated with @GeneratedValue.
  • Fires when: the effective JDBC batch size is greater than 1, the dialect supports sequences (including MariaDB 10.3+), and an identifier uses GenerationType.IDENTITY. Skipped as not applicable on dialects without sequence support (such as Oracle MySQL), where IDENTITY is native and hibernate.jdbc.batch_size still batches UPDATE and DELETE statements.
  • Why it matters: Hibernate must execute each identity insert immediately so it can read back the generated key, preventing JDBC insert batching for those entities despite the configured batch size.
  • Recommendation: switch IDENTITY identifiers to SEQUENCE with a pooled allocationSize so Hibernate can batch inserts, or drop the JDBC batch-size expectation for these entities.

HIB-ID-007 - Composite identifier classes must satisfy the JPA contract

  • Severity: HIGH
  • Inspects: @EmbeddedId attribute types and @IdClass values (including inherited from a superclass).
  • Fires when: a non-record class has no public or protected no-arg constructor; or the class does not override both equals and hashCode.
  • Why it matters: a composite identifier needs stable equality and a construction path that JPA can use. A record supplies its canonical constructor and generated equality methods, so it is exempt from the no-arg-constructor check.
  • Recommendation: for a non-record class, declare a public or protected no-arg constructor and override both equals and hashCode over every identifier field.
  • Persistence 3.2: Serializable is not a composite-key requirement. This check verifies detectable structure, not whether an equality implementation actually compares the correct identifier state.
  • Quarkus/Panache: applies identically - this check inspects only the identifier class via reflection, with no framework-specific behavior.

Mapping

HIB-MAP-001 - One-to-many associations should be bidirectional or join-column based

  • Severity: MEDIUM
  • Inspects: @OneToMany mappings.
  • Fires when: a one-to-many association has neither mappedBy nor @JoinColumn / @JoinColumns.
  • Why it matters: Hibernate models that shape through a join table by default, which often produces extra DML and a less obvious schema.
  • Recommendation: prefer a bidirectional association with @ManyToOne on the child and @OneToMany(mappedBy=...) on the parent so the child's foreign key owns the relationship. If a unidirectional mapping is intentional, add @JoinColumn to drop the join table and review the extra update statements flagged by HIB-MAP-020.

HIB-MAP-002 - Review many-to-many list semantics

  • Severity: MEDIUM
  • Inspects: @ManyToMany mappings and their Java collection type.
  • Fires when: a many-to-many association is declared as List without an explicit persistent order column. An explicitly indexed ordered list is not reported merely for using List.
  • Why it matters: collection semantics affect link-table mutation costs. Hibernate's effective default list semantics and XML mappings can also provide indexing; this declaration-only check does not resolve every case.
  • Recommendation: preserve domain ordering when required. Benchmark mutation behavior; consider Set only when its uniqueness semantics fit, or a link entity when the relationship has its own attributes or lifecycle.

HIB-MAP-003 - Enum attributes should declare an explicit storage strategy

  • Severity: MEDIUM
  • Inspects: enum-valued mapped attributes.
  • Fires when: an enum attribute lacks an observed storage declaration after supported explicit conversion (attribute- or class-level @Convert/@Converts), non-ordinal Hibernate type codes (@JdbcTypeCode with NAMED_ENUM, ENUM, or character/varchar SqlTypes, @JdbcType, or @Type), and @EnumeratedValue exclusions. Absence of a member annotation alone does not establish effective ordinal storage.
  • Why it matters: positional ordinal persistence couples stored values to enum order. Persistence 3.2 can infer STRING storage from a String @EnumeratedValue, and auto-apply/XML converters can replace default storage. Full auto-apply converter resolution remains outside this rule's evidence.
  • Recommendation: use @Enumerated(EnumType.STRING), a database-native enum type (@JdbcTypeCode(SqlTypes.NAMED_ENUM) / SqlTypes.ENUM), or an explicit converter with stable database codes.

HIB-MAP-004 - Many-to-many associations should not cascade remove

  • Severity: HIGH
  • Inspects: @ManyToMany cascade settings.
  • Fires when: the cascade list contains REMOVE or ALL.
  • Why it matters: many-to-many targets usually have independent lifecycles, so delete cascades can remove shared rows instead of only join-table links.
  • Recommendation: remove REMOVE / ALL; use PERSIST / MERGE only when needed, or model the join table as an entity.

HIB-MAP-005 - Many-to-one associations should not cascade remove

  • Severity: HIGH
  • Inspects: @ManyToOne cascade settings.
  • Fires when: the cascade list contains REMOVE or ALL.
  • Why it matters: child-to-parent delete cascade can remove a parent shared by other children.
  • Recommendation: cascade lifecycle operations from aggregate roots to owned children, not from children to parents.

HIB-MAP-006 - One-to-one associations should prefer shared primary keys

  • Severity: MEDIUM (LOW when no lifecycle-dependency signal is detected)
  • Inspects: owning-side @OneToOne mappings.
  • Fires when: the association has no mappedBy, no @MapsId, and the association itself is not the identifier, and it does not target its own entity or another entity of the same @Entity inheritance hierarchy (a self-reference such as Employee.mentor cannot share its primary key). Entities that share only a @MappedSuperclass are separate hierarchies and are still reported. The finding is MEDIUM when the mapping looks lifecycle-dependent (optional=false or cascade REMOVE / ALL) and LOW otherwise.
  • Limitations: any @MapsId attribute is skipped without checking that its value names an identifier attribute. Hibernate 7.4.5 rejects an unmatched @MapsId("name") at bootstrap, so such a mapping does not reach the advisor.
  • Why it matters: dependent one-to-one rows often share the parent lifecycle and can avoid an extra foreign-key/index pair by sharing the primary key.
  • Recommendation: use @MapsId when the child row is lifecycle-dependent on the parent; keep a separate foreign key only when the model requires independent identity.

HIB-MAP-007 - Review TABLE_PER_CLASS polymorphic queries

  • Severity: INFO
  • Inspects: class-level @Inheritance.
  • Fires when: the strategy is InheritanceType.TABLE_PER_CLASS.
  • Why it matters: polymorphic queries over the base type require a UNION across concrete subtype tables.
  • Recommendation: evaluate the polymorphic query workload before changing inheritance strategy. Subtype-only access can make TABLE_PER_CLASS intentional; the declaration does not prove expensive queries are executed.

HIB-MAP-008 - @NotFound(IGNORE) should be reviewed

  • Severity: MEDIUM
  • Inspects: Hibernate @NotFound annotations.
  • Fires when: action=IGNORE.
  • Why it matters: missing target rows are silently treated as null and the association must be resolved eagerly to know whether the target exists.
  • Recommendation: repair referential integrity or model optional data explicitly instead of suppressing missing targets.

HIB-MAP-009 - Persistent attributes should not be Optional

  • Severity: MEDIUM
  • Inspects: mapped attributes whose raw Java type is java.util.Optional.
  • Fires when: an Optional field or property is part of the mapped model.
  • Why it matters: Optional is not a standard portable persistent basic type. A custom type or converter can make a mapping valid; raw Java type alone does not prove a broken runtime mapping.
  • Recommendation: map the underlying nullable type and expose Optional from a non-persistent getter if desired.

HIB-MAP-010 - Review element-collection list ordering and mutation cost

  • Severity: MEDIUM
  • Inspects: @ElementCollection attributes typed as List.
  • Fires when: the list does not declare @OrderColumn - regardless of whether it declares @OrderBy.
  • Limitations: @Immutable does not exempt a list. On the owning entity it leaves collections modifiable; on the collection itself Hibernate 7.4.5 rejects in-place changes but still writes the collection when the owner is persisted or when the attribute is assigned a replacement list.
  • Why it matters: unindexed bag-like collections can need broad delete/reinsert work for some mutations. The effective collection classification and mutation determine the cost; absent @OrderColumn does not prove every change rewrites every row, especially with Hibernate's implicit list-index support.
  • Recommendation: use an order column when persistent positional order is required, or Set when its semantics fit. @OrderBy provides read-time sorting, not an index. Do not combine @OrderBy and @OrderColumn as a generic fix.

HIB-MAP-011 - Entity classes should not be final

  • Severity: INFO
  • Inspects: @Entity classes for the final modifier and their bytecode-enhancement state.
  • Fires when: an entity is declared final and is not proven bytecode-enhanced.
  • Why it matters: final entities are not Jakarta-portable and cannot use subclass proxies for lazy to-one associations. Bytecode enhancement is a valid alternative and is not itself blocked by a final declaration.
  • Recommendation: prefer non-final entities (and open Kotlin entities) when lazy subclass proxies are needed. Bytecode-enhanced entities are exempt.
  • Kotlin note: Kotlin classes are final by default. Before Kotlin 2.3.20 the JPA plugin supplied no-arg constructors but did not itself enable all-open; since 2.3.20 JPA setup enables both. Boot's managed Kotlin 2.3.21 and Quarkus 3.40's 2.4.10 are both at or above 2.3.20, but an application can pin an older Kotlin plugin. The emitted class, not dependency or plugin-name presence, determines finality.

HIB-MAP-012 - SINGLE_TABLE inheritance should declare @DiscriminatorColumn

Retired. Jakarta Persistence defines a valid implicit discriminator column. Requiring an explicit annotation solely for visibility scores a supported default without evidence of an incorrect mapping.

HIB-MAP-013 - String columns should declare explicit length

  • Severity: INFO
  • Inspects: persistent String attributes (excluding identifiers and @Lob fields).
  • Fires when: there is no @Column mapping and no columnDefinition. Reflection cannot distinguish @Column(length = 255) from the annotation's default length, so an existing @Column is treated as an explicit mapping.
  • Why it matters: default generated string DDL may not match domain expectations. Annotation absence does not prove the physical column length: migrations, validation integration, converters and XML overrides can determine it.
  • Recommendation: set @Column(length=...) to match the domain, or use @Lob/columnDefinition for free-text payloads.

HIB-MAP-014 - BigDecimal columns should declare precision and scale

  • Severity: LOW
  • Inspects: persistent BigDecimal attributes.
  • Fires when: @Column(precision=..., scale=...) is missing or precision is zero.
  • Why it matters: when Hibernate generates the schema, it falls back to its dialect defaults, commonly numeric(38,2), so stored values can be rounded to two decimals. The annotation does not affect a column created by a migration, and Hibernate does not round bound values at runtime because the annotation is missing. Effective converters, column definitions and validation metadata are not fully resolved.
  • Recommendation: declare the precision and scale the domain needs, especially when Hibernate generates DDL or a tool derives migrations from the mapping. A mapping annotation is not input validation.

HIB-MAP-015 - Date/time attributes should use java.time

  • Severity: LOW
  • Inspects: persistent attributes typed as java.util.Date, java.util.Calendar, or java.sql temporal types.
  • Fires when: any of those legacy types is detected on a mapped attribute.
  • Why it matters: older temporal types have mutable or less expressive APIs. Persistence 3.2 deprecates @Temporal in favor of modern types, but the correct replacement must preserve date, wall-clock, instant and offset semantics.
  • Recommendation: migrate to java.time (Instant, LocalDate, LocalDateTime, OffsetDateTime, ZonedDateTime) where semantically equivalent. Not every java.time type carries a zone.

HIB-MAP-016 - @ManyToOne should set optional=false when the join column is non-nullable

  • Severity: LOW
  • Inspects: @ManyToOne associations and their @JoinColumn.
  • Fires when: @JoinColumn(nullable=false) is set but optional=false is not.
  • Why it matters: the object-level optionality declaration and column-nullability declaration convey inconsistent intent. This does not prove a secondary SELECT occurs, and neither declaration alone verifies physical constraints.
  • Recommendation: set @ManyToOne(optional=false) whenever the join column is non-nullable.

HIB-MAP-017 - Lazy owning @OneToOne requires bytecode enhancement

Retired. An owning one-to-one holds the foreign key, so Hibernate can create a proxy without enhancement; the check reported a supported lazy mapping. HIB-MAP-018 covers the inverse side, where enhancement does matter.

HIB-MAP-018 - Review lazy inverse @OneToOne without enhancement

  • Severity: MEDIUM
  • Inspects: non-owning (mappedBy) @OneToOne associations and whether the declaring entity is bytecode enhanced.
  • Fires when: relevant enhancement is known absent and an entity declares an explicitly lazy non-owning @OneToOne. Eager declarations and unknown enhancement do not establish a failed lazy-loading request. A mandatory (optional=false) inverse side whose owning side shares the primary key (@MapsId or @PrimaryKeyJoinColumn on the attribute named by mappedBy) is exempt, because Hibernate 7.4.5 proxies it without enhancement. The exemption needs optional=false and an owning side that shares the primary key: with a separate unique foreign key, or with optional=true, Hibernate loads the inverse side eagerly, so the check still fires. A shared key declared through a plain @JoinColumn cannot be detected from declarations.
  • Why it matters: determining whether the inverse row exists can prevent the expected lazy behavior. Query plans, optionality, cache state and access patterns determine actual queries; this declaration does not prove N+1.
  • Recommendation: enable bytecode enhancement, or replace the bidirectional @OneToOne with a shared primary key (@MapsId) and a unidirectional mapping.
  • Quarkus: bytecode enhancement is verified by the adapter's unconditional build-time entity enhancement, so this check never fires there.

HIB-MAP-019 - Missing foreign key indexes

Retired. Annotation declarations cannot verify physical index coverage, and explicit annotation names can still be rewritten by a physical naming strategy. Database structural checks own index evidence; the Hibernate advisor does not duplicate that work by assuming absent @Index means absent database index.

HIB-MAP-020 - Review writable unidirectional one-to-many join-column DML

  • Severity: MEDIUM
  • Inspects: unidirectional @OneToMany associations and their join-column annotations.
  • Fires when: a @OneToMany has no mappedBy, declares a join column, and that join column is not read-only (insertable=false, updatable=false). Composite @JoinColumns is exempt only when every join column is read-only. @Immutable is not an exemption: Hibernate 7.4.5 still issues the join-column UPDATE when an owner with an @Immutable collection is first persisted.
  • Why it matters: this ownership shape can require separate foreign-key UPDATE work depending on the effective mapping and mutation. The declaration alone does not prove an exact INSERT/UPDATE sequence.
  • Recommendation: make the association bidirectional with @ManyToOne on the child and @OneToMany(mappedBy=...) on the parent so the child's foreign key is written in the INSERT. A read-only @JoinColumn(insertable=false, updatable=false) is exempt.

HIB-MAP-021 - Legacy @Where restrictions should be migrated

Retired. Hibernate ORM 7.0 removed @Where and @WhereJoinTable, and every supported runtime uses ORM 7 (Spring Framework 7 requires ORM 7.1 or later; Quarkus 3.40 ships 7.4). Code cannot compile against the removed types, and an annotation whose type is missing at runtime is silently dropped by reflection, so the check could never fire. Migrate any remaining restrictions to @SQLRestriction, @SQLJoinTableRestriction, or @SoftDelete as part of the ORM 7 upgrade.

HIB-MAP-022 - Explicit ordinal enum mappings should be reviewed

  • Severity: INFO
  • Inspects: enum attributes declaring @Enumerated(EnumType.ORDINAL) without an overriding converter, @EnumeratedValue, or non-ordinal @JdbcTypeCode/@JdbcType/@Type.
  • Fires when: ordinal storage is explicit, so the mapping is intentional but still carries a schema-evolution risk.
  • Why it matters: positional ordinal storage changes meaning when enum constants are inserted or reordered. Persistence 3.2 also permits stable numeric codes through @EnumeratedValue; numeric storage is not always position.
  • Recommendation: prefer STRING, a database-native enum, or a stable-code converter. Keep ORDINAL only when append-only ordering is an explicit schema contract.

HIB-MAP-023 - Set element collections of embeddables need equals and hashCode

  • Severity: MEDIUM
  • Inspects: @ElementCollection attributes declared as Set (not SortedSet) and their @Embeddable element class, resolved from the generic type or targetClass.
  • Fires when: the element class is neither a record nor @Immutable and does not override both equals(Object) and hashCode() anywhere below Object. Attributes marked @Immutable or using a custom @CollectionType are skipped, and an unresolvable element type is reported as missing evidence rather than as clean.
  • Why it matters: Hibernate snapshots a Set collection as copies of its elements and looks each current element up in that snapshot. With identity equality no lookup matches, so the collection is treated as changed whenever the owner is flushed: Hibernate deletes every collection row and inserts them all again, and Set.remove with an equal value never matches. Sorted sets compare through their comparator and are not affected.
  • Recommendation: implement equals and hashCode over the embeddable's value state, or model it as a record.

HIB-MAP-024 - @Lob on PostgreSQL stores values as large objects

  • Severity: LOW
  • Inspects: @Lob attributes typed as String, char[], Character[], byte[], or Byte[], in persistence units whose observed dialect is PostgreSQL (or a subclass such as PostgresPlus, but not Spanner's PostgreSQL interface).
  • Fires when: the attribute keeps the default LOB binding. An explicit @JdbcTypeCode with a non-LOB type such as SqlTypes.LONG32VARCHAR is exempt; a converter, @JdbcType, or @Type is reported as missing evidence. A columnDefinition does not exempt the attribute because it changes the DDL, not the binding. JDBC Blob/Clob locators are intentional large-object handles and are not reported. When the dialect is unknown and @Lob attributes exist, the rule reports missing evidence.
  • Why it matters: Hibernate's PostgreSQL dialect maps @Lob to an oid column and binds values through the large-object API. The content lives in pg_largeobject, so deleting or updating the row leaves the old large object behind until it is unlinked, and a text or bytea column created by a migration does not match that binding.
  • Recommendation: remove @Lob unless large-object storage is intended: map long text with @JdbcTypeCode(SqlTypes.LONG32VARCHAR) (text) and binary data as a plain byte[] (bytea). Keep @Lob for deliberate large-object storage, with the lo_manage trigger or vacuumlo cleanup. On PostgreSQL units, HIB-FETCH-005 does not also report the attributes this rule covers.

HIB-MAP-025 - JPA mapping annotations should match the class access type

  • Severity: HIGH
  • Inspects: @Entity, @MappedSuperclass, and non-record @Embeddable classes, their default or explicit @Access (AccessType.FIELD vs AccessType.PROPERTY) placement, and an explicit allowlist of attribute-mapping annotations (@Column, @Formula, @Enumerated, @Lob, @Temporal, @Transient, @Convert, @Converts, @JdbcTypeCode, @JoinColumn, @JoinColumns, @JoinTable, @OneToOne, @ManyToOne, @OneToMany, @ManyToMany, @ElementCollection, @Embedded, @Version, @NaturalId).
  • Fires when: an allowlisted mapping annotation is placed on a getter method while the class uses AccessType.FIELD (without @Access(AccessType.PROPERTY) on the member), or on a backing field while the class uses AccessType.PROPERTY (for example @get:Id in Kotlin without @Access(AccessType.FIELD) on the field). Lifecycle callback methods (@PrePersist, @PostLoad, etc.), record embeddables, framework base classes, and @Transient helper getters/fields without a persistent counterpart are never flagged.
  • Why it matters: Hibernate silently ignores attribute-mapping annotations placed on the wrong member kind unless explicit @Access overrides the access type for that attribute.
  • Recommendation: move the mapping annotations to match the class's access type (field vs getter), or annotate the member with @Access(AccessType.FIELD) / @Access(AccessType.PROPERTY) when mixed access is intentional.

HIB-MAP-027 - Deprecated @GenericGenerator should be replaced

  • Severity: LOW
  • Inspects: class-level and attribute-level @org.hibernate.annotations.GenericGenerator and @GenericGenerators declarations.
  • Fires when: an entity or mapped attribute declares @GenericGenerator or @GenericGenerators on Hibernate ORM 6.5 through 7.x.
  • Why it matters: @GenericGenerator and @GenericGenerators were deprecated in Hibernate ORM 6.5 and 7.0 in favor of type-safe generator annotations.
  • Recommendation: replace @GenericGenerator with a meta-annotated @IdGeneratorType annotation, @UuidGenerator, or standard JPA @SequenceGenerator / @TableGenerator.
  • Version applicability: Hibernate ORM 8 reworked @GenericGenerator and reversed its deprecation; this rule is skipped there, not counted as a conclusive pass. It also skips pre-6.5 versions and preserves missing-version evidence rather than guessing. The rule ID remains reserved and existing 6.5–7.x findings/dismissals retain their meaning. See the ORM 8 migration guide and the actual 8.0.0.CR2 annotation managed by the Quarkus 4.0.1 platform.

HIB-MAP-028 - Deprecated @Cascade annotation should be replaced

  • Severity: LOW
  • Inspects: attribute-level @org.hibernate.annotations.Cascade declarations.
  • Fires when: a mapped attribute declares @org.hibernate.annotations.Cascade.
  • Why it matters: @org.hibernate.annotations.Cascade is @Deprecated(forRemoval = true) since Hibernate ORM 7.0 in favor of standard Jakarta Persistence cascade attributes and @OnDelete.
  • Recommendation: replace @org.hibernate.annotations.Cascade with standard JPA cascade = CascadeType.* on the association annotation (@OneToMany, @ManyToOne, @OneToOne, @ManyToMany), or @OnDelete(action = OnDeleteAction.CASCADE) for database-level foreign-key cascade.

Entity design

HIB-ENTITY-001 - Entities should override equals and hashCode consistently

  • Severity: INFO
  • Inspects: entity classes for detectable equals(Object) and hashCode() overrides.
  • Fires when: an entity overrides one method but not the other.
  • Why it matters: inconsistent equality contracts break sets, maps, and Hibernate collection semantics.
  • Recommendation: implement equals and hashCode as a pair, and review generated identifier semantics before using entities in hash-based collections.

HIB-ENTITY-002 - Versionless optimistic locking should use dynamic updates

Retired. Hibernate ORM 7 refuses to start an application whose entity declares @OptimisticLocking(type = DIRTY) or ALL without @DynamicUpdate (a MappingException, verified on 7.4.5 and 7.4.13, with or without @Immutable), so the declaration can never reach the advisor of a running application and the rule could not fire.

HIB-ENTITY-003 - equals/hashCode should not include lazy associations

Retired. The existence of equality overrides and associations does not show that the methods traverse associations. Safe ID-only implementations also matched. HIB-ENTITY-001 still checks an inconsistent equals/hashCode pair; it does not claim to validate method bodies.

HIB-ENTITY-004 - toString should not include lazy associations

Retired. A toString override plus association declarations does not establish traversal. No method-body analysis proves lazy loading here; safe ID-only implementations must not receive this finding.

HIB-ENTITY-005 - Persistent fields should not be public

  • Severity: LOW
  • Inspects: entity attributes backed by a java.lang.reflect.Field that is public.
  • Fires when: a field-access persistent field is public. A field annotated @Transient is never flagged - it is not written to the database, so it carries none of the accessor-bypass risk this check targets (for example a public @Transient flag field used by a hand-written isNew()/Persistable implementation). Property-access (getter-mapped) attributes are never flagged either, even when the underlying getter method is public - the metamodel resolves those attributes from a Method, not a Field, and public getters are the normal, fully JPA/Hibernate-instrumented way to expose a property-access attribute.
  • Why it matters: public fields can weaken encapsulation and proxy-based interception. Bytecode enhancement can instrument field access; a public field is not proof that Hibernate dirty checking is broken.
  • Recommendation: keep persistent fields private (or package-private) and expose mutators when needed; this preserves application encapsulation without claiming that visibility alone establishes enhancer behavior.
  • Kotlin note: a lateinit var is exempt. Kotlin has no public fields — the property is read and written through its generated getX/setX pair — but the compiler must leave the backing field public so the initialisation check can run from outside the class, and the language offers no way to change that. A property the author did expose, written @JvmField var, generates no accessors at all and is still reported: that is the same encapsulation break a Java public field is.
  • Quarkus/Panache: skipped with verified adapter-provided Panache transformation capability, not merely an unrelated Panache class on the runtime classpath. Panache's active-record entities are meant to be used with public fields; once a Panache extension is present, its build-time bytecode transformation rewrites every public field access on any Hibernate-managed class (not just PanacheEntityBase subclasses) into the matching getter/setter call, so the accessor-bypass concern this check targets does not apply.

HIB-ENTITY-006 - Review primitive-version newness semantics

  • Severity: INFO
  • Inspects: primitive-version declarations in the supported Spring Data JPA newness context.
  • Fires when: a verified standard Spring Data JPA repository domain entity that does not implement Persistable declares a primitive @Version attribute.
  • Why it matters: primitive identifiers and versions are legal. Spring Data recognizes zero-valued numeric primitive identifiers as new, but cannot use a primitive version as a nullable newness signal and falls back to identifier inspection. A wrapper alone does not prove correct custom newness or equality behavior.
  • Recommendation: review the repository's actual save/persist/merge policy when nullable version detection is needed. Do not replace valid primitive IDs merely to satisfy a generic Hibernate warning.
  • Quarkus/Panache: Spring Data newness advice is inapplicable without verified JPA repository metadata.

HIB-ENTITY-007 - Review assigned-ID Spring Data newness

  • Severity: MEDIUM
  • Inspects: Spring Data repository domain entities with assigned identifiers (lacking @GeneratedValue) and no nullable @Version attribute.
  • Fires when: a discovered Spring Data repository domain entity does not implement org.springframework.data.domain.Persistable, including through inherited subinterfaces, within the supported default newness policy. A primitive Version does not supply a nullable signal. Unresolved custom behavior is unknown.
  • Why it matters: with populated assigned identifiers, the standard save policy can choose merge rather than persist. Actual SELECT/INSERT behavior depends on entity state and provider execution; a query before every insert is not guaranteed.
  • Recommendation: consider a nullable version, a correctly managed Persistable<ID> lifecycle, or another deliberate persistence policy. Incorrect custom isNew() handling can itself cause errors; implementing Persistable is not universally required.
  • Quarkus: skipped entirely because no Spring Data repository metadata is available. The concern is specific to Spring Data's repository save() merge-vs-persist decision; Panache's own persist()/persistAndFlush() always issues an INSERT and never probes existence first, so there is nothing to recommend on a Quarkus/Panache app.

HIB-ENTITY-008 - Mutable entities should declare @Version for optimistic locking

  • Severity: INFO
  • Inspects: mapped entities that carry updatable non-identifier persistent state (at least one persistent attribute that is not an @Id, @EmbeddedId, @Version, association, @Transient, or effectively non-updatable via @Column(updatable = false), @JoinColumn(updatable = false), or @CreationTimestamp). Java record entities and Quarkus Data RecordEntity types are also excluded.
  • Fires when: the entity declares no @Version attribute and has not opted into versionless optimistic locking (@OptimisticLocking(DIRTY|ALL)) or @org.hibernate.annotations.Immutable.
  • Why it matters: without optimistic version checks, concurrent read/modify/write operations can overwrite changes. Pessimistic locking, isolation, append-only use and external coordination may already protect the workflow; their absence is not inferred from annotations.
  • Recommendation: add a numeric @Version attribute (for example a Long) so concurrent updates fail fast with an optimistic-lock exception; skip this only for append-only, read-only, or reference data where lost updates cannot occur. Hibernate documents timestamp versions as less reliable (see HIB-ENTITY-010).

HIB-ENTITY-009 - Unique business-key columns should consider @NaturalId

  • Severity: INFO
  • Inspects: @Column(unique = true) attributes and entity-level @Table(uniqueConstraints = @UniqueConstraint(...)) declarations.
  • Fires when: a unique column exists and no attribute on the entity is annotated org.hibernate.annotations.NaturalId.
  • Why it matters: a unique business key (email, ISBN, order number) is frequently queried by value. @NaturalId lets Hibernate resolve the entity by that key through natural-id lookup, which is a well-documented pattern. Any caching benefit needs the second-level or natural-id cache to be enabled and configured, and this check does not assume either. This is advisory, not a defect: a unique column is not always a natural lookup key, so the finding is INFO severity.
  • Recommendation: consider annotating the business-key attribute(s) with @NaturalId so lookups by that value can use Hibernate's natural-id resolution instead of a full query. Adding the annotation does not automatically reroute existing repository queries through natural-id lookup or cache APIs.
  • Quarkus/Panache: applies identically - this check inspects only annotation metadata via reflection.

HIB-ENTITY-010 - Prefer a numeric @Version over a timestamp

  • Severity: INFO
  • Inspects: @Version attributes and their Java type on entities that are not @Immutable.
  • Fires when: the version is a date or time type (java.util.Date, Calendar, or a java.time temporal such as Instant or LocalDateTime).
  • Why it matters: Hibernate documents timestamps as a less reliable optimistic-locking mechanism than version numbers. Two updates within the clock or column precision can produce the same value, and clocks can differ between nodes. A timestamp version is still far better than none, and it is supported.
  • Recommendation: prefer an Integer or Long version and keep a separate audit timestamp when the modification time is needed. Keep a timestamp version when its precision and clock source are deliberate.

HIB-ENTITY-011 - Kotlin entities should not be declared as data class

  • Severity: HIGH
  • Inspects: Kotlin @Entity classes (@kotlin.Metadata) for compiler-generated data class methods (copy$default and component1).
  • Fires when: a mapped Kotlin entity is declared as a data class.
  • Why it matters: Kotlin data class generates equals, hashCode, toString, and copy across primary constructor properties (often including a generated @Id, mutable fields, or lazy associations), which breaks Set contracts across persist() and can trigger unintended lazy initialization or LazyInitializationException.
  • Recommendation: declare the @Entity as a regular class (or open class) and implement equals, hashCode, and toString explicitly over stable identifier state without traversing lazy associations.

HIB-ENTITY-012 - PanacheEntity subclasses should not shadow id or declare custom identifiers

  • Severity: HIGH
  • Inspects: Quarkus PanacheEntity (ORM, Reactive, and Kotlin) subclasses and their declared identifier fields and getters.
  • Fires when: a class extending PanacheEntity declares its own id field or a custom @Id / @EmbeddedId attribute.
  • Why it matters: PanacheEntity already provides @Id @GeneratedValue public Long id;. Redeclaring id or adding another @Id on a PanacheEntity subclass shadows the base field or creates conflicting identifier metadata.
  • Recommendation: extend PanacheEntityBase instead of PanacheEntity when declaring a custom identifier, or remove the duplicate id field to use PanacheEntity's inherited Long id.

Query

All HIB-QUERY rules inspect verified Spring Data JPA repository metadata. Quarkus/Panache does not expose equivalent runtime repository/query metadata with enough fidelity to evaluate these rules reliably, so they remain unavailable on Quarkus rather than guessing from Panache method names or generated bytecode. Mapping, identifier, fetching, configuration, and caching rules still run on Quarkus against the live JPA metamodel.

The JPQL checks deliberately use bounded, conservative lexical analysis rather than a full JPQL parser. Comments and quoted literals are not fetch paths. Queries with nested aliases, subqueries, multiple roots, a root inconsistent with the repository domain, or unresolved rewriting/projection/graph effects may be skipped rather than inferred incorrectly. Named and dynamic queries outside the observed metadata remain outside coverage.

HIB-QUERY-001 - @Modifying bulk queries should clear stale persistence context

  • Severity: INFO
  • Inspects: Spring Data JPA @Modifying annotations on repository methods.
  • Fires when: a supported declared bulk query's merged @Modifying annotation does not set clearAutomatically.
  • Why it matters: the persistence context can hold stale entities after a bulk update or delete, leading to hard-to-diagnose data inconsistencies. flushAutomatically only synchronizes pending changes before the bulk query; it does not evict the stale managed entities afterward.
  • Recommendation: set @Modifying(clearAutomatically=true) (and flushAutomatically=true when pending changes must be applied first), or manage affected state explicitly in a suitably isolated persistence context. Automatic clear detaches managed state and can discard unflushed changes; it is not an unconditional safe fix.

HIB-QUERY-002 - Review streaming query resource lifetime

  • Severity: INFO
  • Inspects: Spring Data repository methods returning java.util.stream.Stream.
  • Fires when: a verified query-backed repository method returns Stream<>.
  • Why it matters: streaming methods keep the underlying JDBC cursor open and only behave correctly inside an open transaction with the caller closing the stream.
  • Recommendation: consume and close the stream within the required transaction, normally using try-with-resources. Read-only transaction hints can help read-only workloads but are not a universal correctness requirement. The method signature does not prove that the caller has failed to do this.

HIB-QUERY-003 - Native Page queries should review count derivation

  • Severity: INFO
  • Inspects: Spring Data @Query(nativeQuery=true), @NativeQuery, and supported composed annotations returning Page<>.
  • Fires when: countQuery is missing.
  • Why it matters: Spring Data can derive a count query for some simple native SQL, but complex SQL can require an explicit count query or JSqlParser support.
  • Recommendation: review the generated count query. Add countQuery = "..." when Spring Data cannot derive a correct count, especially for complex native SQL.

HIB-QUERY-004 - Derived deleteBy methods load entities before deletion

  • Severity: MEDIUM
  • Inspects: Spring Data derived query methods named deleteBy... or removeBy....
  • Fires when: supported query metadata establishes derivation (no @Query, @NativeQuery, named query, entity @NamedQuery/@NamedNativeQuery, or query rewriter) and the method is not a single-row equality delete on the entity's @Id/@EmbeddedId or @NaturalId.
  • Why it matters: Spring Data implements derived deletes by selecting matching entities first and deleting them one by one, which is expensive on large result sets. Single-row key deletes affect at most one entity and are excluded.
  • Recommendation: for bulk removals prefer an explicit @Modifying @Query("delete from ... where ...") with appropriate persistence-context handling; reserve derived deleteBy methods for small or cascading deletes. Bulk DML changes callbacks, cascades and optimistic-lock behavior, so it is not a drop-in replacement.

HIB-QUERY-005 - Eager to-one associations should be JOIN FETCHed in entity-returning queries

  • Severity: INFO
  • Inspects: Spring Data JPQL @Query methods that return multiple whole entities (List/Set/Collection, Stream, Page, Slice, or arrays) on a repository whose domain entity declares an eager @ManyToOne / @OneToOne association (explicit FetchType.EAGER or the to-one default). Mapping-level @Fetch(JOIN) is not a JPQL exemption.
  • Fires when: such a query selects the whole root entity (for example select o from Entity o) but does not JOIN FETCH the eager to-one association.
  • Why it matters: JPQL can require secondary loads to satisfy eager mappings. Repeated targets, caches and actual fetch plans determine the query count; this does not prove a SELECT for every row.
  • Recommendation: prefer changing the association to fetch = FetchType.LAZY (HIB-FETCH-001) unless every caller needs it; only add JOIN FETCH here if eager loading is intentional. Complements HIB-FETCH-001 by pinpointing the specific finders affected.

HIB-QUERY-006 - Paged or streamed reads should prefer DTO projections over whole entities

Retired. Flagged every paged or streamed JPQL @Query returning whole entities (Page<Entity>, Slice<Entity>, or Stream<Entity>), including the second query of the two-step pagination pattern recommended by HIB-FETCH-003 and legitimate domain reads that need managed entity state.

HIB-QUERY-007 - Queries should not JOIN FETCH more than one collection

  • Severity: MEDIUM
  • Inspects: Spring Data repository @Query methods, resolvable JPQL JOIN FETCH paths, and collection/bag metadata on the repository domain entity.
  • Scope: verified declared static bulk UPDATE/DELETE statements in a small readable subset are irrelevant to this rule, without requiring an entity-returning SELECT shape. The subset requires exactly one mapped target, a single-letter alias, one parameter or unsigned-integer assignment for UPDATE, and at most one matching-alias equality predicate. Both assignment and predicate attributes must be observed, non-transient and non-collection. Keywords ignore case, but every alias reference must exactly match the declared alias's case; the proof does not observe strict-JPA compliance settings. Only block comments free of quote/dynamic-expression delimiters and raw -- sequences are ignored. Raw -- anywhere (including arithmetic such as 1--1 or text inside a block comment), quote/dynamic-expression delimiters, more complex DML, malformed or oversized text, named queries and query rewriters remain outside this proof. SQL-style line comments are not HQL comments. Unsupported SELECT shapes still leave required evidence gaps even when no fetch path was recognized.
  • Fires when: a non-native JPQL query JOIN FETCHes two or more collection associations from the same root entity. Runtime bag classification is not established, so presumed bags do not receive a higher-severity exception prediction.
  • Why it matters: simultaneous fetching of actual bags is unsupported, while parallel collections can multiply the row set. Java List declarations alone do not fully establish runtime BAG semantics, so the finding describes the parallel-fetch risk rather than predicting a guaranteed exception.
  • Recommendation: fetch at most one collection per query. Initialize the remaining collections with separate queries, or suitably bounded batch fetching. An entity graph requesting the same parallel collections is not a universal fix, and Set does not eliminate row multiplication.

This scope proof is also used by HIB-QUERY-010; bulk statements can still matter to other rules. It does not erase findings or gaps in other methods or persistence units, nor the advisor's by-design pool limitations. If it discharges the last required gap, the unchanged strict CI assessment can assess a previously skipped optional Hibernate advisor and gate an existing HIGH finding (exit 0 to 3). Remaining gaps still prevent strict assessment; this is not whole-catalogue completeness or relaxed CI policy.

HIB-QUERY-008 - Bulk updates leave @Version unchanged

  • Severity: MEDIUM
  • Inspects: Spring Data repository @Modifying queries targeting entities with a @Version attribute.
  • Fires when: a JPQL/HQL bulk UPDATE query targets an entity that declares an optimistic-locking @Version attribute (including via inheritance or property access) and neither uses UPDATE VERSIONED nor a recognized explicit version assignment in its SET clause. Recognized forms are numeric increments such as e.version = e.version + 1, parameterized increments such as e.version = e.version + :delta (both also accept reversed operands), direct named or numbered positional parameters such as e.version = :nextVersion or e.lastModified = ?1, and timestamp assignments such as e.lastModified = CURRENT_TIMESTAMP or e.lastModified = current_timestamp(). A version predicate only in WHERE, self-assignment, constant resets, and arbitrary expressions do not establish recognized maintenance.
  • Why it matters: bulk updates bypass entity state tracking and direct SQL updates leave @Version unchanged by default. Concurrent transactions holding previously loaded instances will not encounter optimistic locking failures on subsequent flushes, leading to lost updates. clearAutomatically=true only clears the calling persistence context and does not advance the database version.
  • Recommendation: review whether concurrent transactions require version invalidation. Where appropriate, use managed-entity updates, Hibernate's update versioned syntax, or explicitly maintain the version with a numeric increment, a type-compatible current timestamp, or a fresh version parameter (e.g., set e.lastModified = :now). Recognition is a query-shape heuristic, not proof of runtime advancement: the check does not evaluate parameter values, validate expression type compatibility, or guarantee that timestamp precision yields a different value.

HIB-QUERY-009 - Spring Data interface projections should avoid @Value SpEL

  • Severity: MEDIUM
  • Inspects: Spring Data JPA derived or whole-entity repository query methods returning interface projections and the methods declared or inherited on those projection interfaces.
  • Fires when: a projection interface method (including inherited or default methods) is annotated with @org.springframework.beans.factory.annotation.Value, and the repository method does not supply an explicit scalar or native query.
  • Why it matters: @Value SpEL expressions turn an interface projection into an open projection. Spring Data JPA cannot derive a narrow SQL SELECT list for open projections and must load the entire root entity to evaluate the SpEL expression in memory.
  • Recommendation: replace @Value SpEL getters with closed projection property accessors and compute derived values in Java default interface methods.

HIB-QUERY-010 - Review filtered collection fetch joins

  • Severity: MEDIUM
  • Inspects: verified, declared static Spring Data JPA queries returning the whole mapped root entity, with one direct-root @OneToMany or @ManyToMany fetch join.
  • Fires when: the supported WHERE conjunction includes a fetched-alias scalar attribute equality to a named or numbered parameter, string literal, integer, or boolean. Every term must be a mapped scalar equality or an identifier IS NOT NULL check; identifier presence alone does not fire. Root-only filters, ordinary non-fetching joins, singular associations, projections, native queries and verified derived methods do not fire.
  • Why it matters: the query may initialize an incomplete managed collection. Later code can mistake those contents for the complete association. The outcome depends on matching data and persistence-context state: an already initialized full collection may remain full. This is not a prediction of deletion or corruption of unseen rows.
  • Recommendation: use a DTO or separate child query for a filtered view. If the intent is to filter roots, separate that predicate from fetching the complete collection. Review assumptions before modifying the managed association.
  • Bounds: this pilot accepts one direct fetch join and flat conjunctions only. It does not infer restriction from alias words in literals or comments, self-comparisons, tautologies, OR, subqueries (including shadowed aliases), nested joins, functions, parenthesized predicates, or other unsupported shapes. Applicable unsupported shapes, unreadable text, unknown entity/return metadata, named queries and query rewriters retain evidence gaps, not findings or complete passes. The narrow static bulk-DML proof described for HIB-QUERY-007 also excludes those statements here. Query text and literal or parameter values are never included in findings or diagnostics.
  • Platforms: shared engine logic, using existing verified Spring Data JPA metadata on MVC or WebFlux when present; no new Panache or Quarkus repository-query capability is implied.

Configuration

HIB-CONFIG-001 - Open Session in View should be disabled

Retired. Open Session in View is a Spring MVC application setting, not a Hibernate factory option, and the Spring advisor's SPRING-JPA-001 reviews the same activation with richer registration evidence. Keeping both counted one observation against two advisor scores.

HIB-CONFIG-003 - Lazy loading outside transactions should stay disabled

  • Severity: HIGH
  • Inspects: the owning persistence unit's known lazy-loading-outside-transactions setting.
  • Fires when: that observed setting is true; unrelated or absent raw configuration does not establish runtime state.
  • Why it matters: it hides missing fetch plans by opening temporary sessions outside the intended transaction boundary.
  • Recommendation: remove the setting and fetch required data inside transactions with explicit fetch plans or DTO queries.

HIB-CONFIG-004 - JDBC batching should be configured for writes

  • Severity: INFO
  • Inspects: the owning factory's effective JDBC batch size.
  • Fires when: the observed size is less than 2. A batch size of 1 cannot combine multiple statements; an unreadable size is unknown, not disabled batching.
  • Why it matters: write-heavy code otherwise sends insert/update/delete statements one at a time. Even when all writable entities use GenerationType.IDENTITY (leaving inserts unbatched), a positive hibernate.jdbc.batch_size still batches UPDATE and DELETE statements.
  • Recommendation: benchmark a bounded batch size against representative writes. Read-mostly workloads may not benefit; no single range is optimal for every driver or statement shape.
  • Quarkus: absence of quarkus.hibernate-orm.jdbc.statement-batch-size does not establish disabled batching. The observed Hibernate factory value is authoritative, including provider/dialect defaults.

HIB-CONFIG-005 - JDBC batching should order inserts and updates

  • Severity: INFO
  • Inspects: effective factory insert/update ordering when JDBC batching is enabled.
  • Fires when: an observed batch size greater than 1 is configured but a known ordering option is disabled.
  • Why it matters: batches are grouped by SQL/table shape; interleaved entity types reduce batch efficiency.
  • Recommendation: benchmark ordering when writes are interleaved across multiple entity types; sorting adds cost.
  • Quarkus: hibernate.order_inserts/hibernate.order_updates have no first-class quarkus.hibernate-orm.* equivalent, but Quarkus' generic quarkus.hibernate-orm.unsupported-properties."hibernate.order_inserts" (and "hibernate.order_updates") escape hatch reaches the effective factory options this rule reads. A live-boot spike against bootui-quarkus-integration-tests confirmed this end to end: with quarkus.hibernate-orm.jdbc.statement-batch-size and both unsupported-properties entries set, Hibernate's own SessionFactoryOptions.isOrderInsertsEnabled()/isOrderUpdatesEnabled() both report true at runtime, and this rule correctly does not fire.

HIB-CONFIG-006 - Slow query logging should be available in development

  • Severity: INFO
  • Inspects: Hibernate slow-query threshold properties.
  • Fires when: an observed threshold is not positive. Unavailable runtime evidence is not an unset effective default.
  • Why it matters: a local slow-query threshold helps spot expensive SQL before it reaches shared environments.
  • Recommendation: configure a bounded threshold in development and staging profiles.
  • Quarkus: quarkus.hibernate-orm.log.queries-slower-than-ms sets the factory's effective threshold, so a native Quarkus threshold is recognized.

HIB-CONFIG-007 - Hibernate statistics should be enabled when tuning

Retired. Fired in every profile, including production environments where Hibernate and Quarkus advise keeping hibernate.generate_statistics=false to avoid runtime collection overhead, and duplicated the standalone Hibernate Statistics panel and its runtime enable action.

HIB-CONFIG-008 - Connection providers should disable auto-commit explicitly

  • Severity: INFO
  • Inspects: per persistence unit, Hibernate's effective hibernate.connection.provider_disables_autocommit (SessionFactoryOptions#doesConnectionProviderDisableAutoCommit), whether the unit is resource-local or JTA, and the auto-commit default of the HikariCP or Agroal pool behind the unit's connection provider. The unit is matched to its pool by the identity of the DataSource Hibernate holds, after looking through BootUI's SQL Trace proxy and, on Spring, single-target DataSource wrappers (such as the lazy-connection proxy) and static AOP proxies. BootUI never acquires a JDBC connection to discover auto-commit.
  • Fires when: a resource-local unit's pool already hands out connections with auto-commit disabled and the property is off, so Hibernate calls setAutoCommit(false) itself and acquires the connection eagerly.
  • Does not decide (skipped, never a pass): a JTA unit, which owns its auto-commit contract through the transaction manager; an unreadable transaction mode or effective property (a WARNING evidence gap); and a unit whose pool cannot be attributed to exactly one HikariCP or Agroal pool, or whose pool does not report its auto-commit default (an INFO evidence gap that makes the scan PARTIAL). Another pool library, a routing DataSource, a dynamic AOP target, a lazy-connection proxy with a separate read-only target, a third-party wrapper BootUI cannot look through (such as p6spy or datasource-proxy), and Hibernate's built-in pool are all unattributed. Only a pool that already exists is matched; attribution never creates a datasource.
  • Why it matters: when the pool already disables auto-commit, this setting lets Hibernate skip setAutoCommit(false) and delay connection acquisition until the first statement.
  • Recommendation: set hibernate.connection.provider_disables_autocommit=true only because the pool disables auto-commit (HikariCP: spring.datasource.hikari.auto-commit=false). See HIB-CONFIG-021 for the opposite mistake.
  • Spring Boot: Boot 4.1 sets the property to true itself when the pool metadata reports auto-commit disabled and JTA is off, so this check mainly fires when the property was set to false explicitly or Boot could not read the pool's default.
  • Quarkus: Quarkus persistence units coordinate transactions through JTA, so this check is skipped as not applicable; it does not report missing evidence for them.

HIB-CONFIG-009 - Collection-parameter queries should use IN-clause padding

  • Severity: INFO
  • Inspects: Spring Data JPQL query methods with collection parameters and IN predicates.
  • Fires when: such a query exists and hibernate.query.in_clause_parameter_padding is not enabled.
  • Why it matters: variable-length IN predicates can produce many SQL shapes and reduce plan-cache reuse.
  • Recommendation: enable IN-clause parameter padding when the database benefits from statement plan reuse.
  • Quarkus: the effective padding flag reflects quarkus.hibernate-orm.query.in-clause-parameter-padding. The repository-scanning half of this rule only inspects Spring Data JPQL query methods, so it has nothing to flag on a Panache-based Quarkus app regardless of the property value.

HIB-CONFIG-010 - Query caching requires effective region support

  • Severity: HIGH
  • Inspects: effective factory query-cache state and region-factory availability.
  • Fires when: query caching is enabled and effective region infrastructure is known unusable. Missing explicit region-factory configuration is not a failure, and disabled entity second-level caching does not itself prohibit query caching.
  • Why it matters: query-result and timestamp regions require a working provider; entity regions have separate eligibility and concurrency semantics.
  • Recommendation: configure appropriate provider infrastructure or disable query caching. Entity-cache coverage is a separate workload choice; factory query-cache enablement does not prove that any query opts in.
  • Quarkus: Quarkus exposes a single unified quarkus.hibernate-orm.second-level-caching-enabled toggle for second-level/query caching, not a separate query-cache property; the rule reads the resulting effective factory query-cache state and region factory. When enabled, Quarkus supplies its integrated second-level cache implementation even though it does not expose a hibernate.cache.region.factory_class property.

HIB-CONFIG-011 - Review effective cache concurrency strategy

Retired. Neither adapter observes provider-selected cache access strategies or entity eligibility, so in observed mode this rule could never emit a finding and only forced scans of applications using standard @jakarta.persistence.Cacheable without Hibernate's @Cache into PARTIAL status.

HIB-CONFIG-002 - Schema generation should not mutate non-test databases

  • Severity: INFO (can emit MEDIUM, HIGH, or CRITICAL based on profile and value)
  • Inspects: the owning unit's normalized schema database action and active profiles.
  • Evidence: a readable factory properties map with no database-action override establishes Hibernate's default of no database action. Spring Boot omits hbm2ddl.auto for its effective none but keeps an embedded database's effective create-drop when selected. Unavailable reads, invalid action values, and legacy or contributor-specific action keys outside the check's interpretation do not establish the default. A previous finding can resolve on verified absence; missing evidence leaves it unverified.
  • Fires when: a mutating action is observed outside a test profile. Production-like profiles take precedence: destructive drop/drop-and-create actions emit CRITICAL, create-only/update emit HIGH. Dev/local profiles emit INFO; unpinned non-test profiles emit MEDIUM. A profile name does not prove the database is disposable.
  • Why it matters: automatic schema mutation is convenient locally but risky against shared or persistent databases, and destructive actions can remove live schema data. Hibernate hbm2ddl.auto=create is destructive; Jakarta/Quarkus create is CREATE_ONLY and must not be described as guaranteed deletion. In Quarkus 3.33.3.1 an explicitly configured deprecated database.generation takes precedence over schema-management.strategy.
  • Recommendation: use versioned migrations for shared databases and reserve mutating ddl-auto values for disposable test environments.

HIB-CONFIG-012 - SQL logging should be off when a production profile is active

  • Severity: MEDIUM
  • Inspects: spring.jpa.show-sql/hibernate.show_sql (statement output to standard out) and the live org.hibernate.SQL logger at DEBUG or finer.
  • Fires when: either is enabled while a profile named prod, production, staging, prod-*, or *-prod / *-production is active.
  • Why it matters: statement logging adds workload-dependent overhead and can reveal sensitive SQL text. Bound parameter and extracted result values have separate loggers checked by HIB-CONFIG-018; no measured throughput loss is inferred.
  • Recommendation: keep SQL logging off in production-like environments and rely on structured slow-query logging or the database's statement audit.

HIB-CONFIG-013 - Review applicable JDBC temporal binding

  • Severity: LOW
  • Inspects: the owning unit's effective hibernate.jdbc.time_zone and the mapped temporal types.
  • Fires when: no JDBC time zone is configured and the unit maps a type that Hibernate binds through a JDBC Calendar: LocalDateTime, LocalTime, OffsetTime, java.util.Date and its timestamp/time subclasses, or Calendar. Instant binds as UTC, LocalDate and java.sql.Date use no calendar, and zoned or offset date-times follow their time-zone storage strategy, so those types alone do not make the rule applicable.
  • Why it matters: without a configured zone, those bindings use the JVM default time zone, so the stored wall-clock value can change when servers run in different zones. Missing hibernate.jdbc.time_zone is not wrong in itself; driver and converter semantics remain unobserved.
  • Recommendation: choose temporal types and binding semantics deliberately; configure a JDBC zone where needed, rather than treating UTC as a universal fix for every date/time mapping.
  • Quarkus: hibernate.jdbc.time_zone maps to quarkus.hibernate-orm.jdbc.timezone, and the effective factory value is read directly.

HIB-CONFIG-014 - Hibernate's built-in connection pool should not be used

  • Severity: HIGH
  • Inspects: the actual selected Hibernate connection-provider classification.
  • Fires when: the built-in test-oriented connection pool is observed selected. pool_size presence does not select it in preference to a managed DataSource or explicit provider; unknown provider evidence is skipped.
  • Why it matters: the built-in pool is not intended for production use.
  • Recommendation: use the framework's managed DataSource/provider or an appropriate production pool.

HIB-CONFIG-015 - Deferred script initialization should have an intentional order

  • Severity: INFO
  • Inspects: spring.jpa.defer-datasource-initialization and whether Spring Boot registered a DataSourceScriptDatabaseInitializer.
  • Fires when: supported Spring initializer evidence establishes deferred initialization. Ignored Spring property names in Quarkus cannot activate this rule.
  • Why it matters: the property moves script-based datasource initialization until after JPA initialization. That can be intentional with schema validation or externally managed schemas, but the initialization owner and ordering should be explicit.
  • Recommendation: verify that script-based initialization has the intended owner and order. Do not infer that scripts are ineffective solely because Hibernate validates or does not generate the schema.

HIB-CONFIG-016 - Fail on pagination over collection fetch

  • Severity: INFO
  • Inspects: the owning unit's effective hibernate.query.fail_on_pagination_over_collection_fetch guard when the persistence unit maps at least one collection association (@OneToMany or @ManyToMany). Units with zero collection associations are skipped.
  • Fires when: the guard is disabled on a unit with collection associations. The rule reports one configuration finding per unit and never repeats the repository queries that HIB-FETCH-003 owns, so a risky query is not penalized twice.
  • Why it matters: when a limited query fetch-joins a collection and Hibernate cannot apply the limit in SQL, it loads every matching row and limits the result in memory with only a warning. The guard turns that into an exception. Hibernate 7.4 pushes the limit into SQL where the dialect supports it, but a dialect fallback still reaches the guard, and an explicit org.hibernate.limitInMemory=true hint bypasses the guard entirely.
  • Recommendation: consider hibernate.query.fail_on_pagination_over_collection_fetch=true so these queries fail fast during development, and fix the queries HIB-FETCH-003 reports.
  • Quarkus: maps to quarkus.hibernate-orm.query.fail-on-pagination-over-collection-fetch; the effective factory value is read directly.

HIB-CONFIG-017 - Disable SQL formatting in production

  • Severity: LOW
  • Inspects: the effective hibernate.format_sql setting, SQL-logging state, and active Spring or Quarkus profiles.
  • Fires when: a production profile is active, hibernate.format_sql is true, and statement logging is enabled. Binder-only logging does not establish that SQL statements are formatted.
  • Why it matters: Hibernate formats a statement only when it logs that statement. Formatting every verbose SQL log line adds avoidable CPU and allocation work in production.
  • Recommendation: disable hibernate.format_sql when verbose SQL logging is enabled in production.
  • Quarkus: quarkus.hibernate-orm.log.format-sql defaults to true, but it is inert unless quarkus.hibernate-orm.log.sql or an equivalent Hibernate SQL logger is enabled.

HIB-CONFIG-018 - JDBC value logging should be off in production

  • Severity: HIGH
  • Inspects: the effective runtime TRACE state of org.hibernate.orm.jdbc.bind and org.hibernate.orm.jdbc.extract, including inherited levels, plus the active Spring/Quarkus profile. Spring MVC and WebFlux share the same observation source. The legacy org.hibernate.type.descriptor.sql.BasicBinder logger is not inspected by the native adapters.
  • Fires when: a production-like profile is active and either category enables TRACE. One application-wide finding is counted per enabled category, not per persistence unit. DEBUG and OFF do not enable value logging.
  • Why it matters: these categories can expose bound query parameters or extracted result values, including PII, credentials, or tokens. Result logging can expose data even with bind logging off. Logger state establishes the risk, not whether sensitive data was actually logged; BootUI reads no log messages, parameter values, or result values.
  • Recommendation: keep both categories off in production; only enable value logging temporarily in a non-production environment while diagnosing a specific issue.
  • Evidence limits: only the current runtime logger state is observed, not inactive-profile configuration or appender/filter behavior. An unavailable category leaves coverage incomplete without discarding a finding from the other category. An absent finding is not proof of safe production configuration.
  • Quarkus: the Quarkus-native quarkus.hibernate-orm.log.bind-parameters convenience flag raises that same logger to TRACE, so its effective runtime state is detected too - Quarkus's own guide explicitly warns against enabling this in production.
  • Compatibility: the rule id and HIGH severity are unchanged. Existing bind findings keep unit=application|setting=hibernate.type.descriptor.sql.BasicBinder. Result findings use the separate unit=application|setting=org.hibernate.orm.jdbc.extract identity, so dismissing a bind finding cannot hide result logging. A whole-rule dismissal continues to dismiss all HIB-CONFIG-018 findings, including result logging.

HIB-CONFIG-019 - SQL comments should be enabled intentionally

  • Severity: INFO
  • Inspects: hibernate.use_sql_comments.
  • Fires when: generated SQL comments are enabled.
  • Why it matters: comments add statement text. Varying text can affect statement-cache keys, but stable comments need not fragment caches, and the advisor does not measure either traffic or cache behavior.
  • Recommendation: keep comments only when their measured observability benefit outweighs the statement-cache cost.

HIB-CONFIG-020 - Oracle JDBC fetch size should exceed the driver default

  • Severity: INFO
  • Inspects: the owning unit's observed dialect family and effective fetch size. Raw JDBC URLs and credentials are not report evidence.
  • Fires when: Oracle is identifiable and the fetch size is absent or no greater than Oracle JDBC's default of 10.
  • Why it matters: iterating result sets larger than ten rows can require avoidable database roundtrips. PostgreSQL and MySQL have different driver behavior, so this check deliberately does not prescribe a global fetch size.
  • Recommendation: for Oracle queries that commonly return more than ten rows, benchmark a bounded fetch size above 10; retain the default when result sets are consistently small.
  • Quarkus: the effective factory fetch size reflects quarkus.hibernate-orm.jdbc.statement-fetch-size.

HIB-CONFIG-021 - Provider auto-commit setting should match the pool

  • Severity: HIGH
  • Inspects: the same per-unit evidence as HIB-CONFIG-008: the effective hibernate.connection.provider_disables_autocommit, the transaction mode, and the attributed pool's auto-commit default.
  • Fires when: a resource-local unit has the property enabled while its HikariCP or Agroal pool hands out auto-commit connections (autoCommit=true, HikariCP's default). The finding names the unit, the pool and its implementation, and the observed values.
  • Skipped (never a pass): JTA units, an unreadable transaction mode or property, and a pool that cannot be attributed or does not report auto-commit, with the same evidence gaps as HIB-CONFIG-008.
  • Why it matters: the property tells Hibernate that connections are already non-auto-commit, so it never disables auto-commit itself. Against an auto-commit pool each statement then commits on its own and transactions are not atomic.
  • Recommendation: disable auto-commit in the pool (HikariCP: spring.datasource.hikari.auto-commit=false) or remove the property so Hibernate disables auto-commit itself. Quarkus has no quarkus.datasource.jdbc.auto-commit setting for Agroal, so there remove the property.
  • Quarkus: Quarkus units are JTA and Quarkus reports the property as enabled, so this check is skipped for them rather than reporting a contradiction against Agroal's auto-commit default.
  • Limit: only HikariCP and Agroal pools are read, and a pool configured to disable auto-commit by other means (for example a connection initialization statement) is read as the pool reports it.

HIB-CONFIG-022 - Unnecessary explicit standard hibernate.dialect configuration

  • Severity: INFO
  • Inspects: explicit hibernate.dialect / spring.jpa.database-platform configuration and JDBC metadata access flags (hibernate.boot.allow_jdbc_metadata_access and hibernate.temp.use_jdbc_metadata_defaults).
  • Fires when: a built-in org.hibernate.dialect.* class is configured explicitly while startup JDBC metadata access is enabled. Skipped or passed when hibernate.boot.allow_jdbc_metadata_access (or hibernate.temp.use_jdbc_metadata_defaults) is false/disallow, or when a custom or community dialect is used.
  • Why it matters: Hibernate ORM 6 and 7 automatically resolve the appropriate built-in dialect and live database server version from JDBC metadata at startup. Hardcoding a standard dialect class is redundant and can blind Hibernate to live database version capabilities.
  • Recommendation: remove explicit hibernate.dialect / spring.jpa.database-platform settings for built-in org.hibernate.dialect.* dialects unless startup JDBC metadata access is intentionally disabled.
  • Quarkus: Quarkus resolves its dialect at build time and sets hibernate.boot.allow_jdbc_metadata_access=false, so standard Quarkus persistence units are exempt and do not fire.

Caching

HIB-CACHE-001 - Cached entity association coverage should be reviewed

  • Severity: INFO
  • Inspects: entities annotated with @Cacheable or Hibernate @Cache and the entities they associate with.
  • Fires when: a cache-enabled unit contains an observed cached-source declaration pointing to an apparently uncached target. A collection's @Cache stores membership, not the target entity state, and does not exempt its target.
  • Why it matters: loading a cached aggregate can still query an uncached target, but caching target entities and caching collection roles have different semantics and costs. The right coverage depends on real hit rates, mutability, and access patterns.
  • Recommendation: measure cache hit rates and access patterns before caching associated entities or collection roles. Leave mutable or low-hit targets uncached when that better fits the workload.
  • Limit: annotations are not complete provider eligibility evidence; factory enablement does not prove an entity region exists or gets useful hits.

HIB-CACHE-002 - READ_ONLY cache strategy on writable entities is unsafe

  • Severity: MEDIUM
  • Inspects: entities annotated with @Cache(usage = READ_ONLY).
  • Fires when: caching is active and a non-immutable entity has an observed update-oriented declaration. @Immutable with @Version alone is not writable, and disabled caches do not produce active-cache findings.
  • Why it matters: READ_ONLY is unsuitable for managed state that is actually updated. No cache strategy is inferred to observe external writers automatically.
  • Recommendation: switch to READ_WRITE or NONSTRICT_READ_WRITE for mutable entities.

HIB-CACHE-003 - Immutable cached entities should use READ_ONLY

  • Severity: INFO
  • Inspects: entity-level Hibernate @Immutable and @Cache(usage=...).
  • Fires when: an immutable cached entity uses READ_WRITE, NONSTRICT_READ_WRITE, or TRANSACTIONAL.
  • Why it matters: Hibernate documents READ_ONLY as the simplest, safest, and best-performing strategy for immutable entities; mutable strategies add coordination overhead for updates the mapping forbids.
  • Recommendation: consider @Cache(usage = READ_ONLY) for genuinely immutable cached state; do not remove @Immutable merely to silence a cache-efficiency prompt. Disabled caching makes this check inapplicable.

HIB-CACHE-004 - @NaturalIdCache entities should also enable entity second-level caching

  • Severity: MEDIUM
  • Inspects: entities annotated with @org.hibernate.annotations.NaturalIdCache in persistence units where the second-level cache is enabled.
  • Fires when: an entity declares @NaturalIdCache without entity second-level caching (@jakarta.persistence.Cacheable or @org.hibernate.annotations.Cache with a non-NONE strategy).
  • Why it matters: @NaturalIdCache only caches the natural-ID-to-primary-key mapping; without entity second-level caching, resolving an entity by natural ID still hits the database to load the entity state by primary key.
  • Recommendation: add @Cacheable or @org.hibernate.annotations.Cache alongside @NaturalIdCache, or remove @NaturalIdCache if second-level caching of the entity is not desired.

Primary research references

The audit covered every registered rule, including retained workload-dependent advice and the retired identifiers. These are primary implementation/specification sources, not proof of a measured problem in the host application.

TopicSources and version caveats
Exact managed dependenciesSpring Boot 4.1.1 BOM, Quarkus 3.33.3.1 BOM. Application overrides remain possible.
Factory options and batchingORM 7.2.19 options, ORM 7.4.5 options, batching guide. Factory defaults differ from session overrides.
Fetching and entity graphsORM 7.4.5 fetching, Persistence 3.2 entity operations. EAGER and graph requirements do not prove one SQL join.
Collection-fetch paginationORM 7.4.5 hint contract, execution path. Explicit in-memory hints and fallback prevent a blanket 7.4 safety claim.
Identifiers and recordsPersistence 3.2 IdClass, EmbeddedId, Hibernate identifier guide, ORM 7.2.19 UUID styles. Record support and Serializable guidance follow Persistence 3.2.
Mapping defaults and listsPersistence 3.2 discriminator, OrderColumn, ORM 7.4.5 collection semantics. List declarations are not complete runtime collection classification.
Enum/converter semanticsPersistence 3.2 Enumerated, Convert, Converter. Auto-apply and XML resolution remain outside declaration-only checks.
Entity equality and lockingHibernate entity guide, locking guide. General guidance is pinned to 7.2.6; no method-body or workload inference is claimed.
Spring Data queries and newnessSpring Data JPA query methods 4.1.0, primitive identifier handling 4.1.1, primitive version fallback 4.1.1. Custom save/newness and runtime query rewriting need separate evidence.
Cache infrastructure and defaultsORM 7.4.5 cache option construction, provider strategy defaults, Quarkus ORM guide 3.33.0. Cache enablement, region support and actual use are distinct.
Provider auto-commit contractJdbcSettings.CONNECTION_PROVIDER_DISABLES_AUTOCOMMIT, SessionFactoryOptions#doesConnectionProviderDisableAutoCommit, TransactionCoordinatorBuilder#isJta, Boot 4.1.1 HibernateJpaConfiguration (sets the property when the pool disables auto-commit). Quarkus 3.40 Agroal exposes no auto-commit setting.
Pool selection and OSIVORM 7.4.5 provider selection, Boot 4.1.1 OSIV activation, Spring 7.0.9 MVC delegation. Property or configurer-bean presence alone is insufficient.
Quarkus schema actions3.33.3.1 provider precedence, 3.33.3.1 action configuration, ORM 7.2.19 Action. Jakarta create-only and Hibernate destructive create differ.
Audit 2026-10 (effective settings, new rules)ORM 7.4.5 SessionFactoryOptions and SqlStatementLoggerInitiator (effective defaults, legacy slow-query key), PersistentSet and CollectionEntry (HIB-MAP-023), PostgreSQLDialect and PostgreSQL large objects (HIB-MAP-024), SqmSelectionQueryImpl (guard bypassed by limitInMemory), TimestampJdbcType (HIB-CONFIG-013), and the user guide on timestamp versions (HIB-ENTITY-010). Spring Framework 7 requires ORM 7.1+, which retires HIB-MAP-021.
Kotlin and PanacheKotlin 2.3.20 JPA change, Kotlin 2.3.10 plugin, Kotlin 2.3.21 plugin, Panache guide 3.33.0. Compiler output and platform transformation, not classpath presence, establish capability.
Prev
Spring
Next
Database

© 2026 Julien Dubois