Automated summary
This skill provides patterns for building a persistence layer with Spring Data JPA: repositories, entity relationships, derived and @Query queries, pagination, auditing, and transactions.
Strengths
- Covers the full workflow: creating repositories, mapping entities, writing queries, pagination, auditing, and transaction management.
- Supplies directly reusable Java snippets (JpaRepository, findBy..., @Query with @Param, @CreatedDate).
- Includes concrete validation steps: test cascades on a small dataset, check queries with EXPLAIN ANALYZE, index the columns used by pagination.
- Touches advanced topics such as UUID primary keys, multiple databases, and avoiding N+1 queries with @EntityGraph.
Limitations
- Content stays at the code-snippet level: multiple-database setup is mentioned but not detailed.
- Does not cover schema migrations (Flyway/Liquibase) or integration testing strategies.
- Assumes an existing Spring Boot/JPA project and does not address reactive stacks (R2DBC).
Use it when creating or refactoring JPA repositories, entities, and queries in a Spring Boot project, or when fixing pagination, auditing, and transaction issues.
Avoid it for non-JVM projects, reactive persistence, or when the need is schema migration management rather than persistence code.
Security analysis
SafeThis is a pure documentation/pattern skill for Spring Data JPA. Bash is declared but only referenced for benign developer diagnostics (EXPLAIN ANALYZE); there are no installers, curl|sh, file exfiltration, credential access, obfuscated payloads, or destructive commands. Write/Edit are used only for generating Java source, which is expected for a coding skill.
No concerns found
How this analysis is madeExamples
Create a Spring Data JPA repository for my Product entity with a derived query by category, a @Query for products above a given price, and a service method that returns a Page sorted by name.Add JPA auditing with @CreatedDate and @LastModifiedDate to my Order entity and switch its primary key from Long to UUID.Listing orders triggers N+1 queries on the Order -> OrderItem @OneToMany relationship. Show me how to fix it with @EntityGraph and how to verify the improvement with EXPLAIN ANALYZE.name: spring-data-jpa
description: Provides patterns to implement persistence layers with Spring Data JPA. Use when creating repositories, configuring entity relationships, writing queries (derived and @Query), setting up pagination, database auditing, transactions, UUID primary keys, multiple databases, and database indexing.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
Spring Data JPA
Overview
Provides patterns for Spring Data JPA repositories, entity relationships, queries, pagination, auditing, and transactions.
When to Use
Creating repositories with CRUD operations, entity relationships, @Query annotations, pagination, auditing, or UUID primary keys.
Instructions
Create Repository Interfaces
To implement a repository interface:
-
Extend the appropriate repository interface:
@Repository public interface UserRepository extends JpaRepository<User, Long> { // Custom methods defined here } -
Use derived queries for simple conditions:
Optional<User> findByEmail(String email); List<User> findByStatusOrderByCreatedDateDesc(String status); -
Implement custom queries with
@Query:@Query("SELECT u FROM User u WHERE u.status = :status") List<User> findActiveUsers(@Param("status") String status);
Configure Entities
-
Define entities with proper annotations:
@Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 100) private String email; } -
Configure relationships using appropriate cascade types:
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private List<Order> orders = new ArrayList<>();Validation: Test cascade behavior with a small dataset before applying to production data. Verify delete operations don't cascade unexpectedly.
-
Set up database auditing:
@CreatedDate @Column(nullable = false, updatable = false) private LocalDateTime createdDate;
Apply Query Patterns
- Use derived queries for simple conditions
- Use
@Query for complex queries - Return Optional<T> for single results
- Use Pageable for pagination
- Apply
@Modifying for update/delete operations
Manage Transactions
- Mark read-only operations with
@Transactional(readOnly = true) - Use explicit transaction boundaries for modifying operations
- Specify rollback conditions when needed
Validate and Optimize
1. Verify entity configuration:
- Test cascade behavior in a transaction before production deployment
- Validate bidirectional relationships sync correctly
2. Optimize query performance:
- Run
EXPLAIN ANALYZEon queries against large tables - If performance issues detected: add indexes → verify with EXPLAIN → repeat
- Use
@EntityGraphto prevent N+1 queries
3. Validate pagination:
- Ensure indexed columns support pagination queries
- Test with large datasets to verify cursor stability
Examples
Basic CRUD Repository
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Derived query
List<Product> findByCategory(String category);
// Custom query
@Query("SELECT p FROM Product p WHERE p.price > :minPrice")
List<Product> findExpensiveProducts(@Param("minPrice") BigDecimal minPrice);
}
Pagination Implementation
@Service
public class ProductService {
private final ProductRepository repository;
public Page<Product> getProducts(int page, int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("name").ascending());
return repository.findAll(pageable);
}
}
Entity with Auditing
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@CreatedDate
@Column(nullable = false, updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
@CreatedBy
@Column(nullable = false, updatable = false)
private String createdBy;
}
Best Practices
Entity Design
- Use constructor injection exclusively (never field injection)
- Prefer immutable fields with
finalmodifiers - Use Java records (16+) or
@Valuefor DTOs - Always provide proper
@Idand@GeneratedValueannotations - Use explicit
@Tableand@Columnannotations
Performance Optimization
- Use appropriate fetch strategies (LAZY vs EAGER)
- Implement pagination for large datasets
- Use database indexes for frequently queried fields
- Consider using
@EntityGraphto avoid N+1 query problems
Reference Documentation
For comprehensive examples, detailed patterns, and advanced configurations, see:
- Examples - Complete code examples for common scenarios
- Reference - Detailed patterns and advanced configurations
Constraints and Warnings
- Never expose JPA entities directly in REST APIs; always use DTOs to prevent lazy loading issues.
- Avoid N+1 query problems by using
@EntityGraphorJOIN FETCHin queries. - Be cautious with
CascadeType.REMOVEon large collections as it can cause performance issues. - Do not use
EAGERfetch type for collections; it can cause excessive database queries. - Avoid long-running transactions as they can cause database lock contention.
- Use
@Transactional(readOnly = true)for read operations to enable optimizations. - Be aware of the first-level cache; entities may not reflect database changes within the same transaction.
- UUID primary keys can cause index fragmentation; consider using sequential UUIDs or Long IDs.
- Pagination on large datasets requires proper indexing to avoid full table scans.
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/spring-data-jpa-mryiqi87/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/spring-data-jpa-mryiqi87' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/spring-data-jpa-mryiqi87/download' --output '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md.part' && mv '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md.part' '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
Tools declared by the author (check availability in your agent): Read, Write, Edit, Bash, Glob, Grep
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && test -s '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/spring-data-jpa' && cp -R '.skill-downloads/spring-data-jpa-mryiqi87' '.claude/skills/spring-data-jpa'Cursor
test -f '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && test -s '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/spring-data-jpa' && cp -R '.skill-downloads/spring-data-jpa-mryiqi87' '.cursor/skills/spring-data-jpa'Codex
test -f '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && test -s '.skill-downloads/spring-data-jpa-mryiqi87/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/spring-data-jpa' && cp -R '.skill-downloads/spring-data-jpa-mryiqi87' '.agents/skills/spring-data-jpa'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/spring-data-jpa-mryiqi87'openskills read 'spring-data-jpa-mryiqi87'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/spring-data-jpa-mryiqi87/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
React Hook Form Best Practices
Development
Master React Hook Form: avoid anti-patterns, manage subscriptions, and handle reset, dirty state, and controlled inputs correctly.
Emotion to Mantine Migration
Development
Migrate Emotion styled-components to Mantine components with style props and CSS modules. Use when converting .styled.tsx files or removing @emotion imports.
Scope Creep Detector
Development
Analyzes git diffs against a stated intent to detect scope creep, unrelated files, broad PRs, and oversized changes, then suggests keep, split, or justify actions.