Open Source · Java · JPA · Hibernate · AI Engineering

JPA AI

AI-first engineering workflows for Spring Data JPA and Hibernate

The data layer is where N+1 queries hide, migrations break production,
and entity design mistakes compound silently for months.

N+1 detection Migration safety Schema alignment

JPA is the most misused part of the Spring ecosystem.
The bugs don't show up until you hit scale.

Production incidents from migrations gone wrong

Slow endpoints that were fine in code review

Schema drift between JPA entities and the actual database

JPA AI makes the data layer
as disciplined as the rest of the stack.

🧠

Skills

Deep JPA/Hibernate knowledge — entity lifecycle, relationships, queries, performance. 7 skills

🤖

Agents

Specialists for each concern — entity review, migrations, performance, schema drift. 4 agents

📋

Rules

Always-on constraints — naming, fetch strategy, transaction placement, migration safety. 5 rule files

⚙️

Hooks

Automated validation — entity anti-patterns, migration naming, test runner. automated

❌ "looks fine in code review"
✅ caught before merge

7 domain knowledge modules

Each skill file encodes deep expertise for one area of JPA and Hibernate. The AI loads only what's relevant — no bloated context, no guessed patterns.

🔄Hibernate CoreEntity lifecycle, dirty checking, first/second-level cache, LazyInitializationException
🏗️Entity DesignAnnotations, auditing, embeddables, inheritance strategies, enum mapping, equals/hashCode
🔗RelationshipsOneToMany, ManyToOne, ManyToMany, cascade types, Set vs List, bidirectional helpers
🔍JPQL & Queries@Query, projections, DTO constructors, @Modifying, pagination, Criteria API
PerformanceN+1 detection, batch processing, second-level cache, connection pool, SQL logging
🗄️Flyway MigrationsSafe patterns, large-table ops, zero-downtime, CONCURRENTLY, Testcontainers
📦Repository PatternsJpaRepository, Specifications, custom implementations, auditing repositories

4 specialized data-layer reviewers

Each agent focuses on one concern. Use the right one for the right PR — or let /review-jpa coordinate them automatically.

jpa-reviewer reviews

Entity design, relationships, fetch strategy, N+1, transaction placement — the general JPA review for any PR touching the data layer.

migration-reviewer safety

Flyway script review — naming, NOT NULL safety, index concurrency, rollback risk, large-table operations, zero-downtime compatibility.

performance-reviewer performance

Detects N+1 patterns, missing indexes, unbounded queries, inefficient batch operations, and connection pool risks at scale.

schema-reviewer alignment

Validates that JPA annotations (@Column, @Index, @JoinColumn) match the actual DDL defined in migration files. Catches schema drift before deploy.

5 enforcement files

Rules are always-on. They apply to every agent output, every code suggestion, every migration — without being invoked explicitly.

entity-design.mdNaming conventions, required annotations, prohibit ORDINAL enums and EAGER fetching, equals/hashCode on business key.
query-rules.mdNamed parameters only, LAZY by default, N+1 must be fixed before merge, pagination required on unbounded collections.
transaction-rules.mdreadOnly=true on reads, service layer only, no I/O inside transactions, scope and propagation rules.
migration-rules.mdImmutable once applied, naming convention, 3-step NOT NULL, CONCURRENTLY for indexes, no out-of-order.
performance-rules.mdBatch config required, FK indexes mandatory, query timeout, connection pool tuning, SQL logging in dev.
View all rules on GitHub →

Automated data-layer quality gates

Hooks are shell scripts that execute automatically on Claude Code events. Anti-patterns get caught before they're committed.

PostToolUse · entity changes
validate-entities.sh

Scans entity files for ORDINAL enums, EAGER fetching, open-in-view, and dangerous ddl-auto values.

PostToolUse · SQL changes
check-migrations.sh

Validates Flyway naming conventions and detects duplicate version numbers before they reach the CI pipeline.

PostToolUse · code changes
run-tests.sh

Runs mvn test including JPA integration tests. Build failure blocks the next action.

Configure in .claude/settings.json — hooks run outside the AI context, deterministically.

One command. A complete data-layer review.

review-jpa

Reviews the current branch diff against main. Covers entity design, relationships, queries, transactions, migrations, and performance.

What it reviews

Entity column constraints and annotations
Enum mapping — STRING not ORDINAL
Relationship fetch types — LAZY only
Cascade type intentionality
N+1 query risks in service layer
JOIN FETCH / @EntityGraph usage
@Transactional(readOnly = true) on reads
Transaction scope — no I/O inside
Flyway migration naming and safety
NOT NULL 3-step pattern
Index CONCURRENTLY for large tables
Schema drift — JPA vs migration DDL

Real files. Real reviews. Repeatable results.

Actual files from the repository — not pseudocode. Drop them into any Spring Boot project and they work immediately.

.claude/skills/relationships.md (excerpt)
# @OneToMany — Use Set, not List

## Why Set?
## List triggers Hibernate "bag" semantics — duplicate JOIN rows
## when combined with multiple JOIN FETCH operations.

@OneToMany(mappedBy = "customer",
           cascade = CascadeType.ALL,
           orphanRemoval = true,
           fetch = FetchType.LAZY)
private Set<Order> orders = new HashSet<>();

## Bidirectional helper methods — always sync both sides
public void addOrder(Order order) {
    orders.add(order);
    order.setCustomer(this);
}

# Fetch Strategy Rules

@ManyToOne  default: EAGER  →  always override to LAZY
@OneToOne   default: EAGER  →  always override to LAZY
@OneToMany  default: LAZY   →  keep
@ManyToMany default: LAZY   →  keep
.claude/agents/migration-reviewer.md (excerpt)
---
name: migration-reviewer
description: Reviews Flyway scripts for naming, safety, rollback risk,
  zero-downtime compatibility, and large-table operation risks.
skills:
  - migrations-flyway
---

## Migration safety checklist

**Safety rules**
- [ ] New NOT NULL columns: nullable first → backfill → constraint
- [ ] Renames: expand–contract across separate releases
- [ ] No DROP COLUMN in same release as removing code that uses it

**Index operations**
- [ ] Indexes on large tables use CREATE INDEX CONCURRENTLY
- [ ] CONCURRENTLY runs outside a transaction block

**Output format**
[BLOCKER|RISK|SUGGESTION] File: V{n}__{name}.sql
Issue: <what is wrong>
Risk:  <what could go wrong in production>
Fix:   <safe alternative>

End with: SAFE TO RUN / REVIEW REQUIRED / DO NOT RUN
Example /review-jpa output
# JPA Review — feature/add-order-items

## Summary
Adds the OrderItem entity with a ManyToOne to Product and Order.
Two blocking issues in entity design and one migration risk.

## Risk Level
High

## Entity Design Review
⚠ BLOCKER — OrderItem.java: @ManyToOne on `product` uses
FetchType.EAGER. Change to LAZY. Accessing product data
in a list of 1000 items triggers 1000 extra SQL queries.

## Relationship Review
⚠ BLOCKER — Order.java: @OneToMany items uses List<OrderItem>.
Use Set<OrderItem> to prevent Hibernate bag semantics when
JOIN FETCHing multiple collections.

## Migration Review
⚠ RISK — V8__add_unit_price_not_null.sql adds a NOT NULL column
directly. If order_items has existing rows, this will fail.
Add as nullable in V8, backfill in V9, add constraint in V10.

## Final Recommendation
REQUEST CHANGES

The data layer is not plumbing.
It's where the hardest production problems live.

01 / VISIBILITYMake data layer behavior explicit — SQL logging, explain plans, N+1 alerts
02 / SAFETYEvery migration must be reversible in intent, even if forward-only in execution
03 / SCALEDesign queries as if the table has 100M rows, not 100
04 / AILet AI enforce the patterns so engineers can focus on the design decisions

Eduardo Telaya

Senior Software Engineer and international speaker. Building AI-first engineering systems for Java, Spring Boot, and Drupal platforms.

JPA & HibernateDeep expertise in ORM patterns and data layer design
drupal-aiSame AI methodology applied to Drupal
spring-aiFull Spring Boot AI workflow companion
SpeakerInternational conferences

If your Spring Boot data layer has N+1 problems
or migrations that make you nervous to deploy —

This is the system that makes those problems visible before they reach production. Use it. Fork it. Adapt it.

Sponsored by heydru!  —  Enterprise backend engineering and AI-assisted development workflows.