Loading...
Loading...
Implement Spring Data JPA repositories, entities, and queries following modern best practices. Use for creating repositories (only for aggregate roots), writing queries (@Query, DTO projections), custom repositories (Criteria API, bulk ops), CQRS query services, entity relationships, and performance optimization. Covers patterns from simple repositories to advanced CQRS with detailed anti-patterns guidance.
npx skill4agent add a-pavithraa/springboot-skills-marketplace spring-data-jpa| Pattern | When | Read |
|---|---|---|
| Simple Repository | Basic CRUD, 1-2 custom queries | - |
| @Query Repository | Multiple filters, joins, sorting | |
| DTO Projection | Read-only, performance-critical | |
| Custom Repository | Complex logic, bulk ops, Criteria API | |
| CQRS Query Service | Separate read/write, multiple projections | |
| Need | Simple | @Query | DTO | Custom | CQRS |
|---|---|---|---|---|---|
| Basic CRUD | ✅ | ✅ | ❌ | ✅ | ✅ |
| Custom Queries | ❌ | ✅ | ✅ | ✅ | ✅ |
| Best Performance | ✅ | ✅ | ✅✅ | ✅✅ | ✅✅ |
| Complex Logic | ❌ | ❌ | ❌ | ✅ | ✅ |
| Read/Write Separation | ❌ | ❌ | ✅ | ✅ | ✅✅ |
public interface ProductRepository extends JpaRepository<ProductEntity, Long> {
Optional<ProductEntity> findByCode(String code);
List<ProductEntity> findByStatus(ProductStatus status);
}references/query-patterns.mdpublic interface OrderRepository extends JpaRepository<OrderEntity, Long> {
@Query("""
SELECT DISTINCT o
FROM OrderEntity o
LEFT JOIN FETCH o.items
WHERE o.userId = :userId
ORDER BY o.createdAt DESC
""")
List<OrderEntity> findUserOrders(@Param("userId") Long userId);
}assets/query-repository.javareferences/dto-projections.mdpublic record ProductSummary(Long id, String name, BigDecimal price) {}
@Query("""
SELECT new com.example.ProductSummary(p.id, p.name, p.price)
FROM ProductEntity p
WHERE p.status = 'ACTIVE'
""")
List<ProductSummary> findActiveSummaries();assets/dto-projection.javareferences/custom-repositories.md// 1. Custom interface
public interface ProductRepositoryCustom {
List<ProductEntity> findByDynamicCriteria(SearchCriteria criteria);
}
// 2. Implementation (must be named <Repository>Impl)
@Repository
class ProductRepositoryImpl implements ProductRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
// Implementation using Criteria API
}
// 3. Main repository extends both
public interface ProductRepository extends JpaRepository<ProductEntity, Long>,
ProductRepositoryCustom {
Optional<ProductEntity> findBySku(String sku);
}assets/custom-repository.javareferences/cqrs-query-service.md// Repository (package-private) - writes only
interface ProductRepository extends JpaRepository<ProductEntity, ProductId> {
Optional<ProductEntity> findBySku(ProductSKU sku);
}
// QueryService (public) - reads only
@Service
@Transactional(readOnly = true)
public class ProductQueryService {
private final JdbcTemplate jdbcTemplate;
public List<ProductVM> findAllActive() {
return jdbcTemplate.query("""
SELECT id, name, price FROM products
WHERE status = 'ACTIVE'
""",
(rs, rowNum) -> new ProductVM(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("price")
)
);
}
}assets/query-service.javareferences/relationships.md// ✅ GOOD: @ManyToOne (most common)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id", nullable = false)
private Order order;
// ✅ ALTERNATIVE: Just use ID (loose coupling)
@Column(name = "product_id", nullable = false)
private Long productId;
// ❌ AVOID: @OneToMany (query from many side instead)
// Instead: List<OrderItem> items = itemRepository.findByOrderId(orderId);
// ❌ NEVER: @ManyToMany (create join entity instead)
@Entity
public class Enrollment {
@ManyToOne private Student student;
@ManyToOne private Course course;
private LocalDate enrolledAt;
}assets/relationship-patterns.javareferences/performance-guide.md// Use JOIN FETCH
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
List<Order> findWithCustomer();
// Or use DTO projection
@Query("SELECT new OrderSummary(o.id, c.name) FROM Order o JOIN o.customer c")
List<OrderSummary> findSummaries();Pageable pageable = PageRequest.of(0, 20);
Page<Product> page = repository.findByCategory("Electronics", pageable);@Service
@Transactional(readOnly = true)
public class ProductQueryService { }spring.jpa.properties.hibernate.jdbc.batch_size: 25@Service
@Transactional(readOnly = true) // Class-level for read services
public class ProductService {
public List<ProductVM> findAll() {
// Read operations
}
@Transactional // Override for writes
public void createProduct(CreateProductCmd cmd) {
ProductEntity product = ProductEntity.create(cmd);
repository.save(product);
}
}@Transactional(readOnly = true)@Transactional@Transactional@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16-alpine");
@Autowired
private ProductRepository repository;
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Test
void shouldFindProductByCode() {
ProductEntity product = createTestProduct("P001");
repository.save(product);
Optional<ProductEntity> found = repository.findByCode("P001");
assertThat(found).isPresent();
}
}| Don't | Do | Why |
|---|---|---|
| Repository for every entity | Only for aggregate roots | Maintains boundaries |
| Use save() blindly | Understand persist/merge | Avoids unnecessary SELECT |
| Long query method names | Use @Query | Readability |
| findAll() without pagination | Use Page<> or Stream | Memory issues |
| Fetch entities for read views | Use DTO projections | Performance |
| FetchType.EAGER | LAZY + JOIN FETCH | Avoids N+1 |
| @ManyToMany | Use join entity | Allows relationship attributes |
| @Transactional in repository | Put in service layer | Proper boundaries |
| Return entities from controllers | Return DTOs/VMs | Prevents lazy issues |
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
Optional<Order> findByIdWithItems(@Param("id") Long id);references/performance-guide.mdreferences/query-patterns.mdreferences/dto-projections.mdreferences/custom-repositories.mdreferences/cqrs-query-service.mdreferences/relationships.mdreferences/performance-guide.mdassets/query-repository.javadto-projection.javacustom-repository.javaquery-service.javarelationship-patterns.java