본문으로 건너뛰기
Skillpedia
일반 코딩280k · #192

jpa-patterns

하는 일

이 가이드는 JPA와 Hibernate를 사용하는 자바 애플리케이션에서 데이터 접근을 정리하고 최적화하는 방법을 알려 줍니다. 효율적인 데이터 모델을 만들고, 쿼리 속도를 높이며, 트랜잭션과 데이터베이스 연결을 관리하는 방법을 보여 줍니다.

사용하는 경우

  • ✓데이터베이스 테이블과 테이블 사이의 관계를 만들 때.
  • ✓데이터베이스 쿼리가 느리거나 오류가 날 때.
  • ✓애플리케이션이 데이터베이스 연결을 맺고 관리하는 방식을 설정할 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/jpa-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/jpa-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“N+1 문제를 피하려면 JPA 쿼리를 어떻게 최적화할 수 있을까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 가이드는 JPA/Hibernate 어노테이션을 사용해 테이블과 관계를 정의하고 성능을 최적화하는 방법을 코드 예시와 함께 설명합니다. 트랜잭션, 페이지 나누기, 데이터베이스 연결 설정도 다룹니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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.

자주 묻는 질문

N+1 문제란 무엇인가요?

애플리케이션이 먼저 목록을 가져오는 쿼리를 실행한 뒤, 목록의 각 항목마다 별도의 쿼리를 실행해 불필요한 쿼리가 많이 생기는 성능 문제입니다.

‘프로젝션(projection)’이란 무엇인가요?

테이블의 모든 데이터가 아니라 실제로 필요한 데이터만 데이터베이스에 요청하는 방식입니다. 쿼리를 더 빠르게 만들어 줍니다.

‘감사(auditing)’란 무엇인가요?

데이터가 언제 생성되었거나 수정되었는지를 자동으로 기록하는 기능입니다. 변경 사항을 추적하는 데 유용합니다.

상세 정보

작성자의 원본 설명

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot. Use when designing JPA entities or relationships, or when a Hibernate query, transaction, or N+1 problem needs fixing.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#192
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬