jpa-patterns

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

144,923 stars
Complexity: easy

About this skill

This skill equips AI agents with comprehensive knowledge of essential JPA/Hibernate patterns for building robust and performant Spring Boot applications. It covers critical aspects such as effective entity design, managing complex relationships, optimizing database queries, implementing transactional integrity, establishing auditing mechanisms, leveraging indexing for performance, handling pagination, and configuring connection pooling. By leveraging these patterns, an AI can assist developers in generating high-quality, maintainable, and efficient data access layers, adhering to industry best practices.

Best use case

Developers seeking AI assistance for designing database entities, troubleshooting JPA performance issues, implementing common data-related features (like auditing or pagination) in Spring Boot, or generating best-practice-aligned data access code.

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

AI-generated code snippets, architectural advice, or best practice recommendations for JPA/Hibernate, leading to more efficient, scalable, and maintainable Spring Boot applications. The outcome will be code or guidance that reflects established patterns for data persistence.

Practical example

Example input

I need to design an `Order` entity with a one-to-many relationship to `OrderItem` and ensure auditing for creation/update timestamps. Also, how can I implement efficient pagination for fetching orders from the database in a Spring Boot application?

Example output

The AI would provide code examples for the `Order` and `OrderItem` entities, demonstrating `@OneToMany`, `@ManyToOne`, `@CreatedDate`, `@LastModifiedDate`, and then suggest a `Pageable` approach for repository queries.

```java
// Order Entity
@Entity
@Table(name = "orders", indexes = {
  @Index(name = "idx_orders_createdat", columnList = "createdAt")
})
@EntityListeners(AuditingEntityListener.class)
public class Order {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(nullable = false, length = 100)
  private String customerName;

  @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
  private List<OrderItem> items = new ArrayList<>();

  @CreatedDate
  @Column(nullable = false, updatable = false)
  private LocalDateTime createdAt;

  @LastModifiedDate
  @Column(nullable = false)
  private LocalDateTime updatedAt;

  // Getters and Setters...
}

// OrderItem Entity
@Entity
@Table(name = "order_items")
public class OrderItem {
  @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "order_id", nullable = false)
  private Order order;

  @Column(nullable = false, length = 255)
  private String productName;

  @Column(nullable = false)
  private Integer quantity;

  // Getters and Setters...
}

// OrderRepository (Spring Data JPA)
public interface OrderRepository extends JpaRepository<Order, Long> {
  Page<Order> findAll(Pageable pageable);
}

// OrderService snippet for pagination
@Service
public class OrderService {
  @Autowired
  private OrderRepository orderRepository;

  public Page<Order> getPaginatedOrders(int page, int size, String sortBy) {
    Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy).descending());
    return orderRepository.findAll(pageable);
  }
}
```

When to use this skill

  • When designing a new Spring Boot application with JPA, refactoring existing data access code, optimizing slow database operations, implementing features like auditing, soft delete, or setting up efficient pagination for large datasets. It's ideal for scenarios where an AI needs to provide expert guidance on data persistence in Java.

When not to use this skill

  • For non-Java projects, applications not using JPA/Hibernate (e.g., using pure JDBC, NoSQL, or other ORMs), or when the task is unrelated to database interaction and data persistence (e.g., frontend development, infrastructure setup, pure business logic tasks without data storage).

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/jpa-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/affaan-m/everything-claude-code/main/docs/ja-JP/skills/jpa-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/jpa-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How jpa-patterns Compares

Feature / Agentjpa-patternsStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# JPA/Hibernate パターン

Spring Bootでのデータモデリング、リポジトリ、パフォーマンスチューニングに使用します。

## エンティティ設計

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

監査を有効化:
```java
@Configuration
@EnableJpaAuditing
class JpaConfig {}
```

## リレーションシップとN+1防止

```java
@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
```

- デフォルトで遅延ロード。必要に応じてクエリで `JOIN FETCH` を使用
- コレクションでは `EAGER` を避け、読み取りパスにはDTOプロジェクションを使用

```java
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);
```

## リポジトリパターン

```java
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);
}
```

- 軽量クエリにはプロジェクションを使用:
```java
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);
```

## トランザクション

- サービスメソッドに `@Transactional` を付ける
- 読み取りパスを最適化するために `@Transactional(readOnly = true)` を使用
- 伝播を慎重に選択。長時間実行されるトランザクションを避ける

```java
@Transactional
public Market updateStatus(Long id, MarketStatus status) {
  MarketEntity entity = repo.findById(id)
      .orElseThrow(() -> new EntityNotFoundException("Market"));
  entity.setStatus(status);
  return Market.from(entity);
}
```

## ページネーション

```java
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次キャッシュを慎重に検討。退避戦略を検証

## マイグレーション

- FlywayまたはLiquibaseを使用。本番環境でHibernate自動DDLに依存しない
- マイグレーションを冪等かつ追加的に保つ。計画なしに列を削除しない

## データアクセステスト

- 本番環境を反映するために、Testcontainersを使用した `@DataJpaTest` を優先
- ログを使用してSQL効率をアサート: パラメータ値には `logging.level.org.hibernate.SQL=DEBUG` と `logging.level.org.hibernate.orm.jdbc.bind=TRACE` を設定

**注意**: エンティティを軽量に保ち、クエリを意図的にし、トランザクションを短く保ちます。フェッチ戦略とプロジェクションでN+1を防ぎ、読み取り/書き込みパスにインデックスを作成します。

Related Skills

swiftui-patterns

144923
from affaan-m/everything-claude-code

SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。

DevelopmentClaude

perl-patterns

144923
from affaan-m/everything-claude-code

现代 Perl 5.36+ 的惯用法、最佳实践和约定,用于构建稳健、可维护的 Perl 应用程序。

DevelopmentClaude

kotlin-ktor-patterns

144923
from affaan-m/everything-claude-code

Ktor 服务器模式,包括路由 DSL、插件、身份验证、Koin DI、kotlinx.serialization、WebSockets 和 testApplication 测试。

DevelopmentClaude

kotlin-exposed-patterns

144923
from affaan-m/everything-claude-code

JetBrains Exposed ORM 模式,包括 DSL 查询、DAO 模式、事务、HikariCP 连接池、Flyway 迁移和仓库模式。

DevelopmentClaude

rust-patterns

144923
from affaan-m/everything-claude-code

Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.

DevelopmentClaude

laravel-patterns

144923
from affaan-m/everything-claude-code

Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps.

DevelopmentClaude

springboot-patterns

144923
from affaan-m/everything-claude-code

Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.

DevelopmentClaude

django-patterns

144923
from affaan-m/everything-claude-code

Django architecture patterns, REST API design with DRF, ORM best practices, caching, signals, middleware, and production-grade Django apps.

DevelopmentClaude

python-patterns

144923
from affaan-m/everything-claude-code

Python-specific design patterns and best practices including protocols, dataclasses, context managers, decorators, async/await, type hints, and package organization. Use when working with Python code to apply Pythonic patterns.

DevelopmentClaude

postgres-patterns

144923
from affaan-m/everything-claude-code

PostgreSQL database patterns for query optimization, schema design, indexing, and security. Quick reference for common patterns, index types, data types, and anti-pattern detection. Based on Supabase best practices.

DevelopmentClaude

golang-patterns

144923
from affaan-m/everything-claude-code

Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.

DevelopmentClaude

deployment-patterns

144923
from affaan-m/everything-claude-code

Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications. Use when setting up deployment infrastructure or planning releases.

DevelopmentClaude