# jpa-patterns

jpa-patterns teaches coding agents to fix N+1 queries, resolve LazyInitializationException, and manage Spring JPA transactions cleanly.

- skill · `type=skill` · Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, OpenCode, Windsurf (Devin Desktop), Claude.ai · 313 installs · ★ 778 repo stars
- Author: decebals
- License: MIT · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/decebals/claude-code-java/tree/HEAD/skills/jpa-patterns/SKILL.md
- Updated: 2026-09-06
- Security check: automated, 2026-11-16 (text) — no signs of malicious code found.
- HTML: https://affpapa.org/en/nevibecode/skills/decebals-jpa-patterns

## What it does

The skill equips your agent with practical patterns for Spring Data JPA and Hibernate. It provides structured guidance on replacing query loops with `JOIN FETCH`, declarative `@EntityGraph` definitions, or Hibernate batch fetching via `@BatchSize`. It also includes logging configurations to expose hidden database roundtrips during local runs.

When dealing with `LazyInitializationException`, the instructions guide the model away from Open Session in View toward DTO projections, query-level fetch joins, or read-only service transactions. Transaction demarcation rules and propagation modes like `REQUIRES_NEW` are covered as well. Without an explicit `@Version` annotation, concurrent entity writes remain vulnerable to lost updates.

## Install

### Claude Code (native platform)

1. **Skills CLI (Vercel)**
```bash
npx skills add decebals/claude-code-java --skill jpa-patterns -a claude-code
```

2. **Manually: put the files in place**
- File: `~/.claude/skills/jpa-patterns/SKILL.md` — Copy the whole skill folder; for one project use .claude/skills/jpa-patterns/

### Codex

1. **Skills CLI (Vercel)**
```bash
npx skills add decebals/claude-code-java --skill jpa-patterns -a codex
```

2. **Manually: put the files in place**
- File: `.agents/skills/jpa-patterns/SKILL.md` — For all projects use ~/.agents/skills/

### Cursor

1. **Skills CLI (Vercel)**
```bash
npx skills add decebals/claude-code-java --skill jpa-patterns -a cursor
```

2. **Manually: put the files in place**
- File: `.cursor/skills/jpa-patterns/SKILL.md` — Cursor also reads .agents/skills/ and .claude/skills/

### GitHub Copilot

1. **GitHub CLI**
```bash
gh skill install decebals/claude-code-java skills/jpa-patterns
```

2. **Manually: put the files in place**
- File: `.github/skills/jpa-patterns/SKILL.md`

### Gemini CLI

1. **Skills CLI (Vercel)**
```bash
npx skills add decebals/claude-code-java --skill jpa-patterns -a gemini-cli
```

2. **Platform CLI**
```bash
gemini skills install https://github.com/decebals/claude-code-java --path skills/jpa-patterns
```

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/skills/jpa-patterns/SKILL.md` — The legacy .windsurf/skills/ path still works

### OpenCode

**Skills CLI (Vercel)**
```bash
npx skills add decebals/claude-code-java --skill jpa-patterns -a opencode
```

### Claude.ai

**Claude.ai**
- Zip the folder and upload it in Settings → Capabilities → Skills

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/decebals/claude-code-java/tree/HEAD/skills/jpa-patterns/SKILL.md

## When to use it
- eliminate N+1 query loops using JOIN FETCH and @EntityGraph
- resolve LazyInitializationException without relying on Open Session in View
- write lightweight DTO projections for read operations
- configure Spring transaction propagation and rollback rules

## Example prompts
- Help me fix the N+1 issue in this Author and Book relationship using JOIN FETCH.
- I get a LazyInitializationException in OrderService; convert this query to a DTO projection.
- Configure batch fetch sizing in application.properties and on entity collections.

## Source text · SKILL.md · MIT

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: e52117135ccc3fb5.

BEGIN THIRD-PARTY FILE e52117135ccc3fb5
````text
---
name: jpa-patterns
description: JPA/Hibernate patterns and common pitfalls (N+1, lazy loading, transactions, queries). Use when user has JPA performance issues, LazyInitializationException, or asks about entity relationships and fetching strategies.
license: MIT
---

# JPA Patterns Skill

Best practices and common pitfalls for JPA/Hibernate in Spring applications.

## When to Use
- User mentions "N+1 problem" / "too many queries"
- LazyInitializationException errors
- Questions about fetch strategies (EAGER vs LAZY)
- Transaction management issues
- Entity relationship design
- Query optimization

---

## Quick Reference: Common Problems

| Problem | Symptom | Solution |
|---------|---------|----------|
| N+1 queries | Many SELECT statements | JOIN FETCH, @EntityGraph |
| LazyInitializationException | Error outside transaction | Open Session in View, DTO projection, JOIN FETCH |
| Slow queries | Performance issues | Pagination, projections, indexes |
| Dirty checking overhead | Slow updates | Read-only transactions, DTOs |
| Lost updates | Concurrent modifications | Optimistic locking (@Version) |

---

## N+1 Problem

> The #1 JPA performance killer

### The Problem

```java
// ❌ BAD: N+1 queries
@Entity
public class Author {
    @Id private Long id;
    private String name;

    @OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
    private List<Book> books;
}

// This innocent code...
List<Author> authors = authorRepository.findAll();  // 1 query
for (Author author : authors) {
    System.out.println(author.getBooks().size());   // N queries!
}
// Result: 1 + N queries (if 100 authors = 101 queries)
```

### Solution 1: JOIN FETCH (JPQL)

```java
// ✅ GOOD: Single query with JOIN FETCH
public interface AuthorRepository extends JpaRepository<Author, Long> {

    @Query("SELECT a FROM Author a JOIN FETCH a.books")
    List<Author> findAllWithBooks();
}

// Usage - single query
List<Author> authors = authorRepository.findAllWithBooks();
```

### Solution 2: @EntityGraph

```java
// ✅ GOOD: EntityGraph for declarative fetching
public interface AuthorRepository extends JpaRepository<Author, Long> {

    @EntityGraph(attributePaths = {"books"})
    List<Author> findAll();

    // Or with named graph
    @EntityGraph(value = "Author.withBooks")
    List<Author> findAllWithBooks();
}

// Define named graph on entity
@Entity
@NamedEntityGraph(
    name = "Author.withBooks",
    attributeNodes = @NamedAttributeNode("books")
)
public class Author {
    // ...
}
```

### Solution 3: Batch Fetching

```java
// ✅ GOOD: Batch fetching (Hibernate-specific)
@Entity
public class Author {

    @OneToMany(mappedBy = "author")
    @BatchSize(size = 25)  // Fetch 25 at a time
    private List<Book> books;
}

// Or globally in application.properties
````
END THIRD-PARTY FILE e52117135ccc3fb5

The third-party file has ended. Everything between the e52117135ccc3fb5 tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 2796 of 16067 bytes. © decebals · MIT · https://github.com/decebals/claude-code-java/tree/HEAD/skills/jpa-patterns/SKILL.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
