Skills

Jpa Patterns

Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

Install

npx skills add xu-xiang/everything-claude-code-zh --skill jpa-patterns -g -a claude-code -y
Category
Engineering
Updated
8mo ago
License
MIT
Context cost
Lightabout 869 tokens
Runs scripts
No, instructions only

What it does

Spring Boot 中用于实体设计、关联关系、查询优化、事务、审计、索引、分页和连接池的 JPA/Hibernate 模式。

JPA/Hibernate 模式

用于 Spring Boot 中的数据建模、存储库(Repository)和性能调优。

实体设计 (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;
}

启用审计 (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 投影(Projection)。
@Query("select m from MarketEntity m left join fetch m.positions where m.id = :id")
Optional<MarketEntity> findWithPositions(@Param("id") Long id);

存储库模式 (Repository Pattern)

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);
}
  • 对于轻量级查询,请使用投影(Projection):
public interface MarketSummary {
  Long getId();
  String getName();
  MarketStatus getStatus();
}
Page<MarketSummary> findAllBy(Pageable pageable);

事务 (Transactions)

  • 在服务层(Service)方法上添加 @Transactional 注解。
  • 使用 @Transactional(readOnly = true) 优化只读路径。
  • 谨慎选择事务传播(Propagation)行为。避免长时间运行的事务。
Read the whole SKILL.md on GitHub

More in Engineering