首页/后端开发/spring-data-jpa
S

spring-data-jpa

by @giuseppe-trisciuogliov1.0.0
0.0(0)

使用Spring Data JPA实现持久层,通过创建仓库接口提供自动CRUD操作、实体关系和查询方法,简化数据访问。

Spring Data JPAHibernateORMRelational DatabasesSpring BootGitHub
安装方式
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-data-jpa
compare_arrows

Before / After 效果对比

1
使用前
1手动编写大量重复的 JDBCJPA 代码来实现 CRUD 操作和查询,例如:
2```java
3public class UserRepositoryImpl implements UserRepository {
4    @PersistenceContext
5    private EntityManager entityManager;
6
7    @Override
8    public User findById(Long id) {
9        return entityManager.find(User.class, id);
10    }
11
12    @Override
13    public User save(User user) {
14        if (user.getId() == null) {
15            entityManager.persist(user);
16            return user;
17        } else {
18            return entityManager.merge(user);
19        }
20    }
21    // 还有 delete, findAll 等等...
22}
23```
使用后
1使用 Spring Data JPA,只需定义一个接口,框架会自动实现基本的 CRUD 操作和基于方法名的查询,大大减少了样板代码:
2```java
3public interface UserRepository extends JpaRepository<User, Long> {
4    User findByEmail(String email); // 自动生成根据 email 查询的方法
5}
6```

description SKILL.md

spring-data-jpa

Spring Data JPA Overview To implement persistence layers with Spring Data JPA, create repository interfaces that provide automatic CRUD operations, entity relationships, query methods, and advanced features like pagination, auditing, and performance optimization. When to Use Use this Skill when: Implementing repository interfaces with automatic CRUD operations Creating entities with relationships (one-to-one, one-to-many, many-to-many) Writing queries using derived method names or custom @Query annotations Setting up pagination and sorting for large datasets Implementing database auditing with timestamps and user tracking Configuring transactions and exception handling Using UUID as primary keys for distributed systems Optimizing performance with database indexes Setting up multiple database configurations Instructions Create Repository Interfaces To implement a repository interface: Extend the appropriate repository interface: @Repository public interface UserRepository extends JpaRepository<User, Long> { // Custom methods defined here } Use derived queries for simple conditions: Optional findByEmail(String email); List findByStatusOrderByCreatedDateDesc(String status); Implement custom queries with @Query: @Query("SELECT u FROM User u WHERE u.status = :status") List findActiveUsers(@Param("status") String status); Configure Entities Define entities with proper annotations: @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 100) private String email; } Configure relationships using appropriate cascade types: @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true) private List orders = new ArrayList<>(); Set up database auditing: @CreatedDate @Column(nullable = false, updatable = false) private LocalDateTime createdDate; Apply Query Patterns Use derived queries for simple conditions Use @Query for complex queries Return Optional for single results Use Pageable for pagination Apply @Modifying for update/delete operations Manage Transactions Mark read-only operations with @Transactional(readOnly = true) Use explicit transaction boundaries for modifying operations Specify rollback conditions when needed Examples Basic CRUD Repository @Repository public interface ProductRepository extends JpaRepository<Product, Long> { // Derived query List findByCategory(String category); // Custom query @Query("SELECT p FROM Product p WHERE p.price > :minPrice") List findExpensiveProducts(@Param("minPrice") BigDecimal minPrice); } Pagination Implementation @Service public class ProductService { private final ProductRepository repository; public Page getProducts(int page, int size) { Pageable pageable = PageRequest.of(page, size, Sort.by("name").ascending()); return repository.findAll(pageable); } } Entity with Auditing @Entity @EntityListeners(AuditingEntityListener.class) public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @CreatedDate @Column(nullable = false, updatable = false) private LocalDateTime createdDate; @LastModifiedDate private LocalDateTime lastModifiedDate; @CreatedBy @Column(nullable = false, updatable = false) private String createdBy; } Best Practices Entity Design Use constructor injection exclusively (never field injection) Prefer immutable fields with final modifiers Use Java records (16+) or @Value for DTOs Always provide proper @Id and @GeneratedValue annotations Use explicit @Table and @Column annotations Repository Queries Use derived queries for simple conditions Use @Query for complex queries to avoid long method names Always use @Param for query parameters Return Optional for single results Apply @Transactional on modifying operations Performance Optimization Use appropriate fetch strategies (LAZY vs EAGER) Implement pagination for large datasets Use database indexes for frequently queried fields Consider using @EntityGraph to avoid N+1 query problems Transaction Management Mark read-only operations with @Transactional(readOnly = true) Use explicit transaction boundaries Avoid long-running transactions Specify rollback conditions when needed Reference Documentation For comprehensive examples, detailed patterns, and advanced configurations, see: Examples - Complete code examples for common scenarios Reference - Detailed patterns and advanced configurations Constraints and Warnings Never expose JPA entities directly in REST APIs; always use DTOs to prevent lazy loading issues. Avoid N+1 query problems by using @EntityGraph or JOIN FETCH in queries. Be cautious with CascadeType.REMOVE on large collections as it can cause performance issues. Do not use EAGER fetch type for collections; it can cause excessive database queries. Avoid long-running transactions as they can cause database lock contention. Use @Transactional(readOnly = true) for read operations to enable optimizations. Be aware of the first-level cache; entities may not reflect database changes within the same transaction. UUID primary keys can cause index fragmentation; consider using sequential UUIDs or Long IDs. Pagination on large datasets requires proper indexing to avoid full table scans. Weekly Installs359Repositorygiuseppe-trisci…oper-kitGitHub Stars165First SeenFeb 3, 2026Security AuditsGen Agent Trust HubPassSocketPassSnykPassInstalled ongemini-cli276opencode276codex270cursor259github-copilot255claude-code255

forum用户评价 (0)

发表评价

效果
易用性
文档
兼容性

暂无评价,来写第一条吧

统计数据

安装量0
评分0.0 / 5.0
版本1.0.0
更新日期2026年3月17日
对比案例1 组

用户评分

0.0(0)
5
0%
4
0%
3
0%
2
0%
1
0%

为此 Skill 评分

0.0

兼容平台

🔧Claude Code

时间线

创建2026年3月17日
最后更新2026年3月17日