@Repository
@Repository — Data Access Layer
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByCustomerId(Long customerId);
@Query("SELECT o FROM Order o WHERE o.status = :status")
List<Order> findByStatus(@Param("status") OrderStatus status);
@Modifying
@Query("UPDATE Order o SET o.status = :status WHERE o.id = :id")
int updateStatus(@Param("id") Long id, @Param("status") OrderStatus status);
}
What @Repository Provides
- Exception translation — Converts JDBC exceptions to Spring exceptions
- Component scanning — Auto-detected by Spring
- Persistence exception translation — Wraps DataAccessException
Spring Data JPA Methods
| Method | Purpose | Example |
|---|---|---|
findById() |
Get by primary key | repo.findById(1L) |
findAll() |
Get all records | repo.findAll() |
save() |
Create or update | repo.save(entity) |
deleteById() |
Delete by ID | repo.deleteById(1L) |
count() |
Count records | repo.count() |
existsById() |
Check existence | repo.existsById(1L) |
Derived Query Methods
public interface ProductRepository extends JpaRepository<Product, Long> {
// Method name conventions
List<Product> findByCategory(String category);
List<Product> findByPriceBetween(BigDecimal min, BigDecimal max);
List<Product> findByNameContainingIgnoreCase(String name);
List<Product> findByCategoryAndPriceLessThan(String category, BigDecimal price);
Optional<Product> findBySku(String sku);
}
Spring Best Practices
Configuration
- Use properties over YAML for simple configs
- Externalize configuration
- Use profiles for environments
- Validate on startup
Bean Management
- Prefer constructor injection
- Use appropriate scope
- Implement lazy initialization
- Clean up resources
Security
- Use Spring Security
- Implement CSRF protection
- Use method-level security
- Log security events
Key Points
- Understanding @Repository Annotation 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 Annotation in a backend system. Consider scalability, error handling, and production readiness.
Solution
// @Repository Annotation implementation
// Key aspects: validation, error handling, logging, testing
public class RepositoryAnnotation {
// Production-ready implementation
}Identify and handle edge cases for @Repository Annotation. 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 Annotation. 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 @Repository provide beyond component scanning?
2. How do you define a custom query in Spring Data JPA?
3. What is the primary purpose of @Repository Annotation?
4. What is a common mistake when implementing @Repository Annotation?
Flashcards
Question
@Repository purpose?
Click to reveal answer
Answer
Data access layer with exception translation
Question
Spring Data JPA derived queries?
Click to reveal answer
Answer
Methods named like findByCategory, findByPriceBetween — auto-generated queries
Question
What is @Repository Annotation?
Click to reveal answer
Answer
@Repository Annotation is a key concept in backend development.
Question
When to use @Repository Annotation?
Click to reveal answer
Answer
Use @Repository Annotation when building production systems that require reliability, scalability, and maintainability.
Question
@Repository Annotation 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.@Repository marks the data access layer
- 2.Provides exception translation and component scanning
- 3.Spring Data JPA auto-generates queries from method names
- 4.@Query for custom JPQL/native SQL
Interview Tips
- •Know Spring Data JPA method naming conventions
- •Explain @Repository exception translation
Cheat Sheet
@Repository
- Role: Data access layer
- Provides: Exception translation, component scanning
- Spring Data JPA: Auto-generates queries from method names
- Custom: @Query annotation for JPQL/native SQL
- Methods: findById, save, deleteById, findAll