Repository Layer
The repository layer handles all database operations. Spring Data JPA makes this incredibly simple.
Repository Interface
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Spring Data JPA auto-implements these methods:
// save(), findById(), findAll(), deleteById(), count(), existsById()
}
Just by extending JpaRepository, you get all CRUD operations for free.
Custom Query Methods
Spring Data JPA derives queries from method names:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
Optional<Product> findByName(String name);
List<Product> findByCategoryId(Long categoryId);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByNameContainingIgnoreCase(String keyword);
}
JPQL Queries
For complex queries, use @Query with JPQL:
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
@Query("SELECT p FROM Product p WHERE p.category.name = :categoryName AND p.price < :maxPrice")
List<Product> findByCategoryAndMaxPrice(@Param("categoryName") String categoryName,
@Param("maxPrice") BigDecimal maxPrice);
}
Best Practices
Key Principles
- Follow SOLID principles
- Write clean, readable code
- Test thoroughly
- Document decisions
- Monitor in production
Implementation
- Start simple, refactor as needed
- Use established patterns
- Consider trade-offs
- Review with peers
Continuous Improvement
- Learn from incidents
- Update documentation
- Share knowledge
- Mentor others
Key Points
- Understanding Repository is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Repository in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Repository implementation
// Key aspects: validation, error handling, logging, testing
public class Repository {
// Production-ready implementation
}Identify and handle edge cases for Repository. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Repository. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What does extending JpaRepository give you?
2. How does Spring Data JPA derive queries from method names?
3. What is the primary purpose of Repository?
4. What is a common mistake when implementing Repository?
Flashcards
Question
What does JpaRepository provide?
Click to reveal answer
Answer
All CRUD operations, pagination, and sorting for free
Question
What is JPQL?
Click to reveal answer
Answer
Java Persistence Query Language — uses entity/field names instead of table/column names
Question
What is Repository?
Click to reveal answer
Answer
Repository is a key concept in backend development.
Question
When to use Repository?
Click to reveal answer
Answer
Use Repository when building production systems that require reliability, scalability, and maintainability.
Question
Repository best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Extend JpaRepository to get all CRUD operations, pagination, and sorting for free
- 2.Spring Data JPA derives queries from method names (findBy, findByNameContainingIgnoreCase)
- 3.Use @Query annotation with JPQL for complex queries (entity/field names, not table/column)
- 4.Native SQL queries use nativeQuery = true parameter
- 5.Repository methods return Optional for single results, List for multiple results
Interview Tips
- •Explain how Spring Data JPA derives queries from method names
- •Know the difference between JPQL and native SQL queries
- •Discuss when to use custom repository implementations vs standard methods
Cheat Sheet
Repository Layer
- Extend JpaRepository<Entity, ID> for CRUD operations
- Auto-generated methods: save, findById, findAll, deleteById, count
- Query derivation: findByName, findByPriceBetween, findByNameContainingIgnoreCase
- @Query("SELECT p FROM Product p WHERE ...") for JPQL
- @Query(value = "SELECT * FROM ...", nativeQuery = true) for native SQL
- Return types: Optional
for single, List for multiple - Use @Param for named parameters in queries