Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #192

jpa-patterns

Skill này làm gì

Hướng dẫn này dạy cách tổ chức và tối ưu việc truy cập dữ liệu trong ứng dụng Java bằng JPA và Hibernate. Nó chỉ cách tạo mô hình dữ liệu hiệu quả, tăng tốc truy vấn và quản lý giao dịch cùng kết nối cơ sở dữ liệu.

Khi nào nên dùng

  • ✓Khi tạo các bảng cơ sở dữ liệu và mối quan hệ giữa chúng.
  • ✓Khi truy vấn cơ sở dữ liệu chậm hoặc gặp lỗi.
  • ✓Khi cấu hình cách ứng dụng kết nối và quản lý kết nối cơ sở dữ liệu.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/jpa-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tối ưu các truy vấn JPA của tôi để tránh vấn đề N+1?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó đưa ra ví dụ code và giải thích cách dùng annotation của JPA/Hibernate để định nghĩa bảng, mối quan hệ và tối ưu hiệu năng. Nó cũng hướng dẫn cấu hình cho giao dịch, phân trang và kết nối cơ sở dữ liệu.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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.

Câu hỏi thường gặp

Vấn đề N+1 là gì?

Đây là vấn đề về hiệu năng khi ứng dụng thực hiện một truy vấn ban đầu để lấy danh sách, rồi thực hiện một truy vấn riêng cho từng mục trong danh sách, dẫn đến rất nhiều truy vấn không cần thiết.

'Projection' là gì?

Đây là cách yêu cầu cơ sở dữ liệu chỉ trả về dữ liệu bạn thực sự cần, thay vì toàn bộ dữ liệu của một bảng, giúp truy vấn nhanh hơn.

'Auditing' là gì?

Đó là việc tự động ghi lại thời điểm dữ liệu được tạo hoặc chỉnh sửa, hữu ích để theo dõi thay đổi.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#192
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự