Skip to content
intermediatePhase ·

@Repository

Use @Repository to annotate data access classes.

20m
0 problems
Topic Progress0%

@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

  1. Exception translation — Converts JDBC exceptions to Spring exceptions
  2. Component scanning — Auto-detected by Spring
  3. 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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement @Repository Annotation

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
}
@Repository Annotation Edge Cases

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, idempotency
@Repository Annotation Testing Strategy

Write 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 injection

Quiz

1. What does @Repository provide beyond component scanning?

Question 1 options

2. How do you define a custom query in Spring Data JPA?

Question 2 options

3. What is the primary purpose of @Repository Annotation?

Question 3 options

4. What is a common mistake when implementing @Repository Annotation?

Question 4 options

Flashcards

Question

@Repository purpose?

Answer

Data access layer with exception translation

Question

Spring Data JPA derived queries?

Answer

Methods named like findByCategory, findByPriceBetween — auto-generated queries

Question

What is @Repository Annotation?

Answer

@Repository Annotation is a key concept in backend development.

Question

When to use @Repository Annotation?

Answer

Use @Repository Annotation when building production systems that require reliability, scalability, and maintainability.

Question

@Repository Annotation best practices

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