agentleFS
piominpiomin/claude-ai-spring-boot/skills/jpa-patterns/SKILL.md

jpa-patterns

Skill1.4k starsChanged 5 days agoApache-2.0View on GitHub

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.

25 other projects use a version of this, 4 of them edited.

Adopted by

Steady: 0 new projects took it in the last 4 weeks, none the 4 weeks before.thin data

Week of Sep 13: 0 new projectsWeek of Sep 20: 0 new projectsWeek of Sep 27: 0 new projectsWeek of Oct 4: 0 new projectsWeek of Oct 11: 0 new projectsWeek of Oct 18: 0 new projectsWeek of Oct 25: 0 new projectsWeek of Nov 1: 0 new projects
Sep 2026Oct 2026Nov 2026
New projects taking a version of this file each week, over the 8 weeks our latest run read: only 0 in all, so this is a hint, not a trend.

Most recently taken up by

Who's talking about piomin/claude-ai-spring-boot

The biggest 5 of 17 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 17

Talked about on GitHub (17 times).

On GitHub · 17

12 more on GitHub

Used with

Projects with it also use nuxt4-patterns, agent-payment-x402 and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • loulanyueSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 10 projects that use this

  • TironFoxSkill

    agent-payment-x402

    Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.

    Also in 6 projects that use this

  • TironFoxSkill

    openclaw-persona-forge

    为 OpenClaw AI Agent 锻造完整的龙虾灵魂方案。根据用户偏好或随机抽卡, 输出身份定位、灵魂描述(SOUL.md)、角色化底线规则、名字和头像生图提示词。 如当前环境提供已审核的生图 skill,可自动生成统一风格头像图片。 当用户需要创建、设计或定制 OpenClaw 龙虾灵魂时使用。 不适用于:微调已有 SOUL.md、非 OpenClaw 平台的角色设计、纯工具型无性格 Agent。 触发词:龙虾灵魂、虾魂、OpenClaw 灵魂、养虾灵魂、龙虾角色、龙虾定位、 龙虾剧本杀角色、龙虾游戏角色、龙虾 NPC、龙虾性格、龙虾背景故事、 lobster soul、lobster character、抽卡、随机龙虾、龙虾 SOUL、gacha。

    Also in 5 projects that use this

  • royaluniondesign-sysSkill

    configure-ecc

    Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.

    Also in 11 projects that use this

  • junimnjwSkill

    ralphinho-rfc-pipeline

    RFC-driven multi-agent DAG execution pattern with quality gates, merge queues, and work unit orchestration.

    Also in 10 projects that use this

  • RojiosSkill

    dart-flutter-patterns

    Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.

    Also in 6 projects that use this

The file

We split this skill into the rules it gives an agent

7 rules. 0 are common, 1 is distinctive, and 6 are very specific to this project.

  • 0

    Common

    Most of the 21 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Create, update and delete of a record with a relation are @Transactional, and the response is mapped inside the transaction.

    line 247
  2. Very specific:

    Read paths load the relation with @EntityGraph(attributePaths = "assignee") on findById and findAll(Specification, Pageable), so a page …

    line 248
  3. Very specific:

    Test none → A, A → B and A → none against the real database (Testcontainers).

    line 249
  4. Distinctive:

    Never include all fields: mutable fields change the hash, lazy associations trigger loads

    line 414
  5. Very specific:

    Use instanceof (not getClass()) in equals so Hibernate proxies compare equal

    line 415
  6. Very specific:

    If the link carries data (enrolment date, grade), map the join table as its own entity with two @ManyToOne.

    line 457
  7. Very specific:

    Call from a @Transactional service method

    line 597

“Common” is measured: kept by at least 6 in 10 of the 21 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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

ProblemSymptomSolution
N+1 queriesMany SELECT statementsJOIN FETCH, @EntityGraph
LazyInitializationExceptionError outside transactionDTO projection, JOIN FETCH (not Open Session in View)
Slow queriesPerformance issuesPagination, projections, indexes
Dirty checking overheadSlow updatesRead-only transactions, DTOs
Lost updatesConcurrent modificationsOptimistic locking (@Version), version from the client compared explicitly
Entity lost from HashSet after persistequals/hashCode on generated idNatural key, or id-based with constant hashCode
Stale entities after bulk updateOld values read in same transaction@Modifying(clearAutomatically = true)
Schema driftEntities and DB out of sync across environmentsFlyway migrations + ddl-auto: validate (see conventions)
500 after a successful update of a relationLazyInitializationException on an uninitialized proxy@Transactional write, map the response inside it

N+1 Problem

The #1 JPA performance killer

The Problem

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

// ✅ 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

// ✅ 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

// ✅ 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
spring.jpa.properties.hibernate.default_batch_fetch_size=25

Detecting N+1

# Enable SQL logging to detect N+1
spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true

logging:
  level:
    org.hibernate.SQL: DEBUG
    org.hibernate.orm.jdbc.bind: TRACE

Lazy Loading

FetchType Basics

@Entity
public class Order {

    // LAZY: Load only when accessed (default for collections)
    @OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
    private List<OrderItem> items;

    // EAGER: Always load immediately (default for @ManyToOne, @OneToOne)
    @ManyToOne(fetch = FetchType.EAGER)  // ⚠️ Usually bad
    private Customer customer;
}

Best Practice: Default to LAZY

// ✅ GOOD: Always use LAZY, fetch when needed
@Entity
public class Order {

    @ManyToOne(fetch = FetchType.LAZY)  // Override EAGER default
    private Customer customer;

    @OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
    private List<OrderItem> items;
}

LazyInitializationException

// ❌ BAD: Accessing lazy field outside transaction
@Service
public class OrderService {

    public Order getOrder(Long id) {
        return orderRepository.findById(id).orElseThrow();
    }
}

// In controller (no transaction)
Order order = orderService.getOrder(1L);
order.getItems().size();  // 💥 LazyInitializationException!

Solutions for LazyInitializationException

Solution 1: JOIN FETCH in query

// ✅ Fetch needed associations in query
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
Optional<Order> findByIdWithItems(@Param("id") Long id);

Solution 2: @Transactional on service method

// ✅ Keep transaction open while accessing
@Service
public class OrderService {

    @Transactional(readOnly = true)
    public OrderDTO getOrderWithItems(Long id) {
        Order order = orderRepository.findById(id).orElseThrow();
        // Access within transaction - lazy collection loads here
        int itemCount = order.getItems().size();
        return new OrderDTO(order, itemCount);
    }
}

Solution 3: DTO projection (best for read-only)

// ✅ Avoid lazy loading entirely - query only what you need
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("SELECT new pl.piomin.services.dto.OrderSummary(o.id, o.status, SIZE(o.items)) " +
           "FROM Order o WHERE o.id = :id")
    Optional<OrderSummary> findSummaryById(@Param("id") Long id);
}

Disable Open Session in View

Spring Boot enables OSIV by default (and logs a warning at startup). It keeps the persistence context and a DB connection open until the response is written, so lazy loads in controllers or JSON serialization "work" while hiding N+1 queries.

spring:
  jpa:
    open-in-view: false  # fetch what the response needs in the service layer

Writing a Record with a Relation (OSIV off)

With open-in-view: false, a write that loads the record outside a transaction and then calls save merges a detached entity; a newly set @ManyToOne becomes an uninitialized proxy, and mapping the response throws LazyInitializationException. The change is already committed, but the client gets a 500, and its next save meets a stale version.

@Transactional  // load, change, save and map in one persistence context
public TaskResponse update(Long id, TaskUpdateRequest request) {
    Task task = find(id);
    Person assignee = request.assigneeId() == null ? null : personRepository.findById(request.assigneeId())
            .orElseThrow(() -> unknownReference("assigneeId"));  // 400, not 404: the request is invalid
    checkVersion(task, request.version());
    task.replaceWith(request, assignee);
    return TaskResponse.from(repository.saveAndFlush(task));  // map inside the transaction
}
  • Create, update and delete of a record with a relation are @Transactional, and the response is mapped inside the transaction.
  • Read paths load the relation with @EntityGraph(attributePaths = "assignee") on findById and findAll(Specification, Pageable), so a page does not issue one query per row.
  • Test none → A, A → B and A → none against the real database (Testcontainers). A mocked @WebMvcTest never sees a JPA proxy, and A → B is the case that fails.

Transaction Management

Read-Only Optimization

@Service
@Transactional(readOnly = true)  // Default for all methods
public class ProductService {
    private final ProductRepository repo;

    public ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    public List<Product> findAll() {
        return repo.findAll();  // Read-only: skips dirty checking
    }

    @Transactional  // Override: read-write for mutations
    public Product create(ProductRequest request) {
        var product = new Product();
        product.setName(request.name());
        return repo.save(product);
    }
}

Self-Invocation Pitfall

// ❌ BAD: @Transactional ignored on self-invocation
@Service
public class OrderService {

    public void processOrders(List<Long> ids) {
        for (Long id : ids) {
            processOrder(id);  // Calls via 'this', not proxy - no transaction!
        }
    }

    @Transactional
    public void processOrder(Long id) {
        // This @Transactional is ignored when called from processOrders()
    }
}

// ✅ GOOD: Extract to separate bean
@Service
public class OrderService {
    private final OrderProcessor processor;

    public OrderService(OrderProcessor processor) {
        this.processor = processor;
    }

    public void processOrders(List<Long> ids) {
        for (Long id : ids) {
            processor.processOrder(id);  // Calls via proxy
        }
    }
}

@Service
public class OrderProcessor {
    @Transactional
    public void processOrder(Long id) {
        // Transaction works correctly
    }
}

Optimistic Locking

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private BigDecimal price;

    @Version
    private Long version;  // Hibernate checks this on update

    // getters/setters
}

// The client sends the version it read; compare it explicitly
@Service
public class ProductService {
    private final ProductRepository repo;

    public ProductService(ProductRepository repo) {
        this.repo = repo;
    }

    @Transactional
    public ProductResponse update(Long id, ProductUpdateRequest request) {
        Product product = repo.findById(id)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Product " + id + " not found"));
        if (!request.version().equals(product.getVersion())) {
            throw new ObjectOptimisticLockingFailureException(Product.class, id);
        }
        product.setName(request.name());
        product.setPrice(request.price());
        return ProductResponse.from(repo.saveAndFlush(product));  // flushed: the response has the new version
    }
}
  • @Version only protects the window between this transaction's read and its commit. Across HTTP requests, the client sends the version it read and the service compares it: Hibernate ignores a version set on a managed entity, so product.setVersion(request.version()) does not detect a stale update.
  • Do not wrap save() in try/catch (OptimisticLockingFailureException) inside a @Transactional method: the UPDATE runs at flush or commit, after the try block has ended. Let the exception propagate and map ObjectOptimisticLockingFailureException to 409 in the @RestControllerAdvice (Problem Details without errors, so a client can tell it from a field conflict).
  • Return the entity's version in every response, and require it in the update request.

Entity Design

equals() and hashCode()

// ✅ Business key: stable before and after persist
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NaturalId  // org.hibernate.annotations.NaturalId
    @Column(nullable = false, unique = true, updatable = false)
    private String isbn;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        return o instanceof Book other && isbn != null && isbn.equals(other.isbn);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(isbn);
    }
}

// ✅ No natural key: id-based equality, constant hashCode
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    return o instanceof Order other && id != null && id.equals(other.id);
}

@Override
public int hashCode() {
    return getClass().hashCode();  // unchanged when the id is assigned on persist
}
  • Never include all fields: mutable fields change the hash, lazy associations trigger loads
  • Use instanceof (not getClass()) in equals so Hibernate proxies compare equal

Bidirectional Relationships

@Entity
public class Author {

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books = new ArrayList<>();

    // ✅ Keep both sides in sync - the @ManyToOne side owns the FK
    public void addBook(Book book) {
        books.add(book);
        book.setAuthor(this);
    }

    public void removeBook(Book book) {
        books.remove(book);
        book.setAuthor(null);
    }
}

@Entity
public class Book {

    @ManyToOne(fetch = FetchType.LAZY)  // ✅ No cascade on the child side
    @JoinColumn(name = "author_id")
    private Author author;
}
// ✅ @ManyToMany: Set (a List makes Hibernate delete and re-insert the whole join table)
//    and PERSIST/MERGE only - never REMOVE or ALL
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "student_course",
    joinColumns = @JoinColumn(name = "student_id"),
    inverseJoinColumns = @JoinColumn(name = "course_id"))
private Set<Course> courses = new HashSet<>();

If the link carries data (enrolment date, grade), map the join table as its own entity with two @ManyToOne.

Common Mapping Mistakes

// ❌ BAD: CascadeType.ALL on @ManyToOne - removing a book removes its shared author
@ManyToOne(cascade = CascadeType.ALL)
private Author author;

// ❌ BAD: toString() touching a lazy collection - extra query,
//    LazyInitializationException outside a transaction, StackOverflowError on bidirectional links
@Override
public String toString() {
    return "Author{id=" + id + ", books=" + books + "}";
}

// ✅ GOOD: basic columns only
@Override
public String toString() {
    return "Author{id=" + id + ", name='" + name + "'}";
}

Modern Hibernate Features

Jakarta Persistence

// Always use jakarta.persistence.* (not javax.persistence.*)
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;

UUID Generation

@Entity
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)  // Native UUID generation
    private UUID id;

    private String name;

    // getters/setters
}

Soft Delete

// Built-in soft delete support
@Entity
@SoftDelete  // Adds 'deleted' boolean column, filters automatically
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    // getters/setters
}

// Custom column name
@Entity
@SoftDelete(columnName = "is_active", converter = NumericBooleanConverter.class)
public class Product {
    // ...
}

Record as DTO in Queries

// Records work natively in JPQL constructor expressions
public record ProductSummary(Long id, String name, BigDecimal price) {}

public interface ProductRepository extends JpaRepository<Product, Long> {

    @Query("SELECT new pl.piomin.services.dto.ProductSummary(p.id, p.name, p.price) " +
           "FROM Product p WHERE p.price > :minPrice")
    List<ProductSummary> findExpensiveProducts(@Param("minPrice") BigDecimal minPrice);
}

Query Best Practices

Pagination

// ✅ Always paginate unbounded queries
public interface UserRepository extends JpaRepository<User, Long> {

    Page<User> findByActiveTrue(Pageable pageable);

    Slice<User> findByRole(String role, Pageable pageable);  // No COUNT query
}

// Usage
Page<User> page = userRepository.findByActiveTrue(
    PageRequest.of(0, 20, Sort.by("createdAt").descending())
);

Spring Data Projections

// Interface-based projection - fetches only declared fields
public interface UserNameOnly {
    String getFirstName();
    String getLastName();
}

public interface UserRepository extends JpaRepository<User, Long> {
    List<UserNameOnly> findAllByActiveTrue();
}

Bulk Updates and Deletes

Bulk JPQL bypasses the persistence context, lifecycle callbacks, cascades and @Version checks.

public interface OrderRepository extends JpaRepository<Order, Long> {

    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Query("UPDATE Order o SET o.status = :status WHERE o.createdAt < :before")
    int archiveOlderThan(@Param("status") OrderStatus status, @Param("before") Instant before);
}
  • flushAutomatically writes pending changes before the query; clearAutomatically detaches stale entities after it
  • Call from a @Transactional service method
  • Increment the version explicitly (SET o.version = o.version + 1) if concurrent writers rely on optimistic locking

Quick Decision Guide

SituationSolution
N+1 in loopJOIN FETCH or @EntityGraph
LazyInitializationExceptionJOIN FETCH in query or @Transactional on service
Read-only queries slow@Transactional(readOnly = true)
Concurrent updates over HTTP@Version, client sends version, compare, 409 on mismatch
Entity equality@NaturalId, or id-based equals with constant hashCode
Bidirectional associationadd*/remove* helper methods; Set for @ManyToMany
Bulk UPDATE/DELETE@Modifying(clearAutomatically = true, flushAutomatically = true)
Lazy loads in web layerspring.jpa.open-in-view=false
Unbounded result setPagination with PageRequest
Need only few columnsDTO projection or interface projection
Soft delete required@SoftDelete
UUID primary key@GeneratedValue(strategy = GenerationType.UUID)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.