Communitygithub.com

jpa-patterns

JPA/Hibernate 패턴: 엔티티 설계, 관계 설정, 쿼리 최적화, 트랜잭션, 감사, 인덱싱, 페이징, 커넥션 풀링을 위한 스킬입니다. JPA 엔티티나 관계를 설계하거나, Hibernate 쿼리, 트랜잭션, N+1 문제를 해결해야 할 때 사용합니다.

jpa-patterns란 무엇인가요?

이 스킬은 Spring Boot 기반 애플리케이션에서 JPA와 Hibernate를 효과적으로 사용하기 위한 모범 사례를 제공합니다. 엔티티 설계, 관계 매핑(@OneToMany, @ManyToOne, @ManyToMany), N+1 문제 방지, 쿼리 최적화, 트랜잭션 관리, 감사(Auditing), 소프트 삭제, 페이징, 커넥션 풀링(HikariCP), 2차 캐싱, 마이그레이션(Flyway/Liquibase), 테스트 등 데이터 액세스 계층 전반을 다룹니다. 특히 성능 튜닝에 중점을 두어, fetch 전략과 DTO 프로젝션을 통한 N+1 방지, 인덱스 설계, 배치 처리(batch_size), 읽기 전용 트랜잭션 최적화 등의 실용적인 코드 예제와 설정을 제공합니다. 이 스킬은 Claude Code, Cursor, Codex 등 AI 코딩 에이전트에서 활성화되어, JPA 엔티티 설계나 Hibernate 관련 문제 해결 시 구체적인 패턴과 표준 코드를 제안하는 데 사용됩니다.

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

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

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

문서

JPA/Hibernate 패턴

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

활성화 시점

  • JPA 엔티티 및 테이블 매핑 설계
  • 관계 정의 (@OneToMany, @ManyToOne, @ManyToMany)
  • 쿼리 최적화 (N+1 방지, fetch 전략, 프로젝션)
  • 트랜잭션, 감사 또는 소프트 삭제 구성
  • 페이징, 정렬 또는 커스텀 리포지토리 메서드 설정
  • 커넥션 풀링(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;
}

감사 기능 활성화:

@Configuration
@EnableJpaAuditing
class JpaConfig {}

관계와 N+1 방지

@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
  • 기본적으로 지연 로딩 사용; 필요 시 쿼리에서 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) 방식으로 작성; 계획 없이 컬럼을 삭제하지 말 것

데이터 액세스 테스트

  • 프로덕션 환경과 유사한 테스트를 위해 @DataJpaTest와 Testcontainers 사용 선호
  • 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬