Communitygithub.com

jpa-patterns

JPA/Hibernate 패턴: 엔티티 설계, 관계 매핑, 쿼리 최적화, 트랜잭션, 감사, 인덱싱, 페이징, 풀링 등 Spring Boot에서의 모범 사례를 제공합니다. JPA 엔티티나 관계를 설계하거나, Hibernate 쿼리, 트랜잭션, N+1 문제를 해결할 때 사용하세요.

jpa-patterns란 무엇인가요?

이 스킬은 Spring Boot 환경에서 JPA와 Hibernate를 효과적으로 사용하기 위한 포괄적인 패턴 가이드를 제공합니다. 엔티티 설계, 연관 관계 매핑(@OneToMany, @ManyToOne, @ManyToMany), N+1 쿼리 방지, 트랜잭션 관리, 감사(Auditing), 소프트 삭제, 페이징, 정렬, 커스텀 리포지토리 메서드 등의 핵심 영역을 다룹니다. 또한 HikariCP 기반의 커넥션 풀 튜닝, 2차 캐시 설정, 데이터베이스 인덱싱 전략, Flyway/Liquibase를 통한 마이그레이션 모범 사례를 포함합니다. 개발자는 이 스킬을 통해 성능 최적화, 데이터 무결성 유지, 확장 가능한 데이터 액세스 계층을 구축할 수 있으며, @DataJpaTest와 Testcontainers를 활용한 실제 환경과 유사한 테스트 방법도 함께 얻을 수 있습니다.

지원 대상~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/jpa-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

JPA/Hibernate 패턴

Spring Boot에서 데이터 모델링, 리포지토리, 성능 튜닝을 위해 사용합니다.

활성화 시점

  • JPA 엔티티 및 테이블 매핑 설계
  • 관계 정의 (@OneToMany, @ManyToOne, @ManyToMany)
  • 쿼리 최적화 (N+1 방지, fetch 전략, 프로젝션)
  • 트랜잭션, 감사(Auditing), 소프트 삭제 구성
  • 페이징, 정렬, 커스텀 리포지토리 메서드 설정
  • 커넥션 풀 (HikariCP) 또는 2차 캐시 튜닝

엔티티 설계

@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;
}

감사(Auditing) 활성화:

@Configuration
@EnableJpaAuditing
class JpaConfig {}

관계와 N+1 방지

@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
  • 기본적으로 지연 로딩(lazy loading) 사용; 필요 시 쿼리에서 JOIN FETCH 사용
  • 컬렉션에는 EAGER 사용을 피하고, 읽기 경로에는 DTO 프로젝션 사용
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);

리포지토리 패턴

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);
}
  • 가벼운 쿼리를 위해 프로젝션 사용:
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);

트랜잭션

  • 서비스 메서드에 @Transactional 어노테이션 사용
  • 읽기 경로에는 @Transactional(readOnly = true)를 사용하여 최적화
  • 전파(propagation)를 신중하게 선택하고, 장시간 실행되는 트랜잭션을 피하세요
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}

페이징

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

커서 기반 페이징을 위해 JPQL에 id > :lastId 조건과 정렬을 포함하세요.

인덱싱 및 성능

  • 공통 필터(status, slug, 외래 키)에 인덱스 추가
  • 쿼리 패턴과 일치하는 복합 인덱스 사용 (status, created_at)
  • select * 사용을 피하고, 필요한 컬럼만 프로젝션
  • saveAll과 hibernate.jdbc.batch_size를 사용하여 쓰기 작업 배치 처리

커넥션 풀링 (HikariCP)

권장 설정:

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

PostgreSQL LOB 처리를 위해 다음을 추가:

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

캐싱

  • 1차 캐시는 EntityManager별로 유지되므로 트랜잭션 간에 엔티티를 보관하지 않도록 주의
  • 읽기가 많은 엔티티의 경우 2차 캐시를 신중하게 고려하고, 제거(eviction) 전략을 반드시 검증하세요

마이그레이션

  • Flyway 또는 Liquibase 사용; 프로덕션에서 Hibernate 자동 DDL에 의존하지 마세요
  • 마이그레이션을 멱등성(idempotent) 있고 추가(additive)적으로 유지하며, 계획 없이 컬럼을 삭제하지 마세요

데이터 액세스 테스트

  • 프로덕션 환경을 반영하기 위해 Testcontainers와 함께 @DataJpaTest 사용 선호
  • 로그를 통해 SQL 효율성 확인: logging.level.org.hibernate.SQL=DEBUG 및 logging.level.org.hibernate.orm.jdbc.bind=TRACE 설정으로 파라미터 값 확인

기억하세요: 엔티티는 간결하게, 쿼리는 의도적으로, 트랜잭션은 짧게 유지하세요. fetch 전략과 프로젝션으로 N+1을 방지하고, 읽기/쓰기 경로에 맞게 인덱싱하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

관련 스킬