spring-data-jpa
БесплатноБез исполняемых скриптовНе проверенProvides patterns to implement persistence layers with Spring Data JPA. Use when creating repositories, configuring entity relationships, writing queries…
от giuseppe-trisciuoglio★ 373 звезды на GitHubОб этом скилле
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
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
@EntityGraphor `J
Установить spring-data-jpa в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditBashGlobGrepВложенные файлы
FAQ
Что делает скилл spring-data-jpa?
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.
Как установить скилл spring-data-jpa?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл spring-data-jpa запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic