jpa-patterns by affaan-m/everything-claude-code
npx skills add https://github.com/affaan-m/everything-claude-code --skill jpa-patterns用于 Spring Boot 中的数据建模、存储库和性能调优。
@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 {}
@OneToMany(mappedBy = "market", cascade = CascadeType.ALL, orphanRemoval = true)
private List<PositionEntity> positions = new ArrayList<>();
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
默认使用延迟加载;需要时在查询中使用 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) 以进行优化
谨慎选择传播行为;避免长时间运行的事务
@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 进行批量写入推荐属性:
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
@DataJpaTest 配合 Testcontainers 以模拟生产环境logging.level.org.hibernate.SQL=DEBUG 和 logging.level.org.hibernate.orm.jdbc.bind=TRACE 以查看参数值请记住:保持实体简洁、查询有针对性、事务简短。通过获取策略和投影防止 N+1 问题,并为您的读写路径建立索引。
每周安装量
784
代码仓库
GitHub 星标数
69.1K
首次出现
2026 年 1 月 30 日
安全审计
安装于
opencode640
codex625
gemini-cli616
claude-code567
github-copilot563
cursor541
Use for data modeling, repositories, and performance tuning in Spring Boot.
@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 {}
@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);
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);
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); }
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.
status, slug, foreign keys)status, created_at)select *; project only needed columnssaveAll and hibernate.jdbc.batch_sizeRecommended 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
@DataJpaTest with Testcontainers to mirror productionlogging.level.org.hibernate.SQL=DEBUG and logging.level.org.hibernate.orm.jdbc.bind=TRACE for parameter valuesRemember : Keep entities lean, queries intentional, and transactions short. Prevent N+1 with fetch strategies and projections, and index for your read/write paths.
Weekly Installs
784
Repository
GitHub Stars
69.1K
First Seen
Jan 30, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode640
codex625
gemini-cli616
claude-code567
github-copilot563
cursor541
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装