Java persistence

From makifbaysal/tasktrooper · View interactive version

Java persistence is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when a Java service reads or writes the database - JPA/Hibernate and Panache/Spring Data mapping, transaction boundaries, pagination and avoiding N+1 and entity-over-the-wire leaks

How to use this skill

Skill file

Java Persistence (JPA / Panache / Spring Data)

Overview

Persistence is where Java services most often leak — lazy-loading exceptions, N+1 queries, entities serialized over HTTP, pagination applied in memory. Keep persistence at the repository boundary and mapped deliberately.

Core principle: Entities are a persistence detail. They never cross the HTTP boundary and they never carry business logic that belongs in the domain. Every list query is bounded AND the bound is honored by the SQL, not by Java code truncating a full result set.

Mapping surface

| Concern | Quarkus (Panache) | Spring Data |

|---------|-------------------|-------------|

| Entity | @Entity + PanacheEntityBase or plain @Entity | @Entity |

| Repository | implements PanacheRepository<Task> | extends JpaRepository<Task, UUID> |

| Query | find("status", s) / HQL | derived methods / @Query |

| Transaction | @Transactional on the service | @Transactional on the service |

| Pagination | .page(Page.of(n, size)) | Pageable / Page<T> |

| Optimistic lock | @Version | @Version |

| Schema management (non-test) | quarkus.hibernate-orm.schema-management.strategy=none (or validate; property renamed from database.generation in 3.23) | spring.jpa.hibernate.ddl-auto=validate |

Rules

Worked Example — killing an N+1 without breaking pagination

// ❌ N+1: one query for projects, then one per project for its tasks
List<Project> projects = repo.findAll(pageable).getContent();
projects.forEach(p -> total += p.getTasks().size());   // lazy hit per row

// ❌ "fixed" with a fetch join but now unbounded: Hibernate pages in memory
@Query("select p from Project p left join fetch p.tasks")
Page<Project> findAllWithTasks(Pageable pageable);   // HHH90003004

// ✅ page the roots first (no collection fetch), then fetch by id with the join
Page<UUID> ids = repo.findIds(pageable);
List<Project> page = repo.findByIdInWithTasks(ids.getContent());

Add a query-count assertion (Hibernate Statistics, see java-testing-junit-mockito) so the N+1 can't creep back in, and a test on the test profile with hibernate.query.fail_on_pagination_over_collection_fetch=true so an accidental collection-fetch-plus-page regresses loudly instead of just getting slow.

Common Mistakes

Red Flags

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.