Spring data jpa

From giuseppe-trisciuoglio/developer-kit · View interactive version

Spring data jpa is an AI agent skill from the GitHub repository giuseppe-trisciuoglio/developer-kit. Provides patterns to implement persistence layers with Spring Data JPA. Use when creating repositories, configuring entity relationships, writing queries (derived and `@Query`), setting up pagination, database auditing, transactions, UUID primary keys, multiple databases, and database indexing.

How to use this skill

Skill file

Spring Data JPA

Overview

Provides patterns for Spring Data JPA repositories, entity relationships, queries, pagination, auditing, and transactions.

When to Use

Creating repositories with CRUD operations, entity relationships, @Query annotations, pagination, auditing, or UUID primary keys.

Instructions

Create Repository Interfaces

To implement a repository interface:

  1. Extend the appropriate repository interface:

```java

@Repository

public interface UserRepository extends JpaRepository<User, Long> {

// Custom methods defined here

}

```

  1. Use derived queries for simple conditions:

```java

Optional<User> findByEmail(String email);

List<User> findByStatusOrderByCreatedDateDesc(String status);

```

  1. Implement custom queries with @Query:

```java

@Query("SELECT u FROM User u WHERE u.status = :status")

List<User> findActiveUsers(@Param("status") String status);

```

Configure Entities

  1. Define entities with proper annotations:

```java

@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long id;

@Column(nullable = false, length = 100)

private String email;

}

```

  1. Configure relationships using appropriate cascade types:

```java

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)

private List<Order> orders = new ArrayList<>();

```

Validation: Test cascade behavior with a small dataset before applying to production data. Verify delete operations don't cascade unexpectedly.

  1. Set up database auditing:

```java

@CreatedDate

@Column(nullable = false, updatable = false)

private LocalDateTime createdDate;

```

Apply Query Patterns

  1. Use derived queries for simple conditions
  2. Use @Query for complex queries
  3. Return Optional<T> for single results
  4. Use Pageable for pagination
  5. Apply @Modifying for update/delete operations

Manage Transactions

  1. Mark read-only operations with @Transactional(readOnly = true)
  2. Use explicit transaction boundaries for modifying operations
  3. Specify rollback conditions when needed

Validate and Optimize

1. Verify entity configuration:

2. Optimize query performance:

3. Validate pagination:

Examples

Basic CRUD Repository

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    // Derived query
    List<Product> findByCategory(String category);

    // Custom query
    @Query("SELECT p FROM Product p WHERE p.price > :minPrice")
    List<Product> findExpensiveProducts(@Param("minPrice") BigDecimal minPrice);
}

Pagination Implementation

@Service
public class ProductService {
    private final ProductRepository repository;

    public Page<Product> 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

Performance Optimization

Reference Documentation

For comprehensive examples, detailed patterns, and advanced configurations, see:

Constraints and Warnings

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.