PluginBench
Skill
Pass
Audit score 90

jpa-patterns

affaan-m/everything-claude-code

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, and performance tuning in Spring Boot.

What is jpa-patterns?

Provides best practices for designing JPA entities, managing relationships, optimizing queries to prevent N+1 problems, configuring transactions, and tuning connection pooling and caching. Use when building data access layers in Spring Boot applications.

  • Design entities with proper mappings, indexes, and auditing using @Entity, @Table, and @EntityListeners
  • Define and optimize relationships (@OneToMany, @ManyToOne, @ManyToMany) with lazy loading and JOIN FETCH strategies
  • Prevent N+1 query problems through fetch strategies, DTO projections, and intentional query design
  • Configure transactions with @Transactional, read-only optimization, and appropriate propagation settings
  • Implement pagination, sorting, and custom repository methods using Spring Data JPA
  • Tune connection pooling (HikariCP), indexing strategies, and second-level caching for performance

How to install jpa-patterns

npx skills add https://github.com/affaan-m/everything-claude-code --skill jpa-patterns
Prerequisites
  • Spring Boot project with Spring Data JPA dependency
  • Relational database (PostgreSQL, MySQL, etc.)
  • Flyway or Liquibase for schema migrations (recommended for production)
Claude Code
Cursor
Windsurf
Cline

How to use jpa-patterns

  1. 1.Define entities with @Entity, @Table, and appropriate column constraints and indexes
  2. 2.Enable JPA auditing with @EnableJpaAuditing and @CreatedDate/@LastModifiedDate annotations
  3. 3.Create repository interfaces extending JpaRepository with custom @Query methods
  4. 4.Use lazy loading by default; add JOIN FETCH or projections only where needed to prevent N+1
  5. 5.Annotate service methods with @Transactional and use readOnly=true for read paths
  6. 6.Configure HikariCP pool settings and batch size in application.properties for your workload
  7. 7.Add indexes on frequently filtered columns and foreign keys matching your query patterns

Use cases

Good for
  • Designing a multi-entity domain model with complex relationships and audit requirements
  • Optimizing slow queries by identifying N+1 problems and applying fetch strategies or projections
  • Setting up pagination and filtering for large result sets in REST APIs
  • Configuring connection pools and batch operations for high-throughput data access
  • Implementing soft deletes and audit trails using entity listeners and custom columns
Who it's for
  • Backend developers building Spring Boot applications with relational databases
  • Data architects designing JPA entity models and database schemas
  • Performance engineers optimizing query execution and connection pooling
  • Teams migrating to or maintaining Spring Data JPA repositories

jpa-patterns FAQ

How do I prevent N+1 query problems?

Use lazy loading by default, apply JOIN FETCH in @Query methods when you need related entities, or use DTO projections for read-heavy paths. Avoid EAGER loading on collections.

Should I use EAGER or LAZY loading for relationships?

Default to LAZY loading. Use EAGER only for single-valued associations if truly necessary. For collections, always use LAZY and fetch explicitly with JOIN FETCH when needed.

What indexing strategy should I follow?

Add indexes on columns used in WHERE clauses (status, slug, foreign keys) and consider composite indexes matching your query patterns. Avoid indexing low-cardinality columns.

How do I handle pagination efficiently?

Use PageRequest with Pageable parameters in repository methods. For cursor-like pagination, include id > :lastId conditions with proper ordering.

What connection pool settings should I use?

Start with maximum-pool-size=20, minimum-idle=5, connection-timeout=30000ms. Adjust based on your workload and database capacity. Use HikariCP (Spring Boot default).

Full instructions (SKILL.md)

Source of truth, from affaan-m/everything-claude-code.


name: jpa-patterns description: JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot. metadata: origin: ECC

JPA/Hibernate Patterns

Use for data modeling, repositories, and performance tuning in Spring Boot.

When to Activate

  • Designing JPA entities and table mappings
  • Defining relationships (@OneToMany, @ManyToOne, @ManyToMany)
  • Optimizing queries (N+1 prevention, fetch strategies, projections)
  • Configuring transactions, auditing, or soft deletes
  • Setting up pagination, sorting, or custom repository methods
  • Tuning connection pooling (HikariCP) or second-level caching

Entity Design

@Entity
@Table(name = "markets", indexes = {
  @Index(name = "idx_markets_slug", columnList = "slug", unique = true)
})
@EntityListeners(AuditingEntityListener.class)
public class MarketEntity {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false, length = 200)
  private String name;

  @Column(nullable = false, unique = true, length = 120)
  private String slug;

  @Enumerated(EnumType.STRING)
  private MarketStatus status = MarketStatus.ACTIVE;

  @CreatedDate private Instant createdAt;
  @LastModifiedDate private Instant updatedAt;
}

Enable auditing:

@Configuration
@EnableJpaAuditing
class JpaConfig {}

Relationships and N+1 Prevention

@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
  • Default to lazy loading; use JOIN FETCH in queries when needed
  • Avoid EAGER on collections; use DTO projections for read paths
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);

Repository Patterns

public interface MarketRepository extends JpaRepository<MarketEntity, Long> {
  Optional<MarketEntity> findBySlug(String slug);

  @Query("select m from MarketEntity m where m.status = :status")
  Page<MarketEntity> findByStatus(@Param("status") MarketStatus status, Pageable pageable);
}
  • Use projections for lightweight queries:
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);

Transactions

  • Annotate service methods with @Transactional
  • Use @Transactional(readOnly = true) for read paths to optimize
  • Choose propagation carefully; avoid long-running transactions
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}

Pagination

PageRequest page = PageRequest.of(pageNumber, pageSize, Sort.by("createdAt").descending());
Page<MarketEntity> markets = repo.findByStatus(MarketStatus.ACTIVE, page);

For cursor-like pagination, include id > :lastId in JPQL with ordering.

Indexing and Performance

  • Add indexes for common filters (status, slug, foreign keys)
  • Use composite indexes matching query patterns (status, created_at)
  • Avoid select *; project only needed columns
  • Batch writes with saveAll and hibernate.jdbc.batch_size

Connection Pooling (HikariCP)

Recommended properties:

spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.validation-timeout=5000

For PostgreSQL LOB handling, add:

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

Caching

  • 1st-level cache is per EntityManager; avoid keeping entities across transactions
  • For read-heavy entities, consider second-level cache cautiously; validate eviction strategy

Migrations

  • Use Flyway or Liquibase; never rely on Hibernate auto DDL in production
  • Keep migrations idempotent and additive; avoid dropping columns without plan

Testing Data Access

  • Prefer @DataJpaTest with Testcontainers to mirror production
  • Assert SQL efficiency using logs: set logging.level.org.hibernate.SQL=DEBUG and logging.level.org.hibernate.orm.jdbc.bind=TRACE for parameter values

Remember: Keep entities lean, queries intentional, and transactions short. Prevent N+1 with fetch strategies and projections, and index for your read/write paths.