Skip to content
intermediate Phase · Java Backend Development

Repository

Understand the repository layer that handles database access.

35m
0 problems
Topic Progress 0%

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

  1. Follow SOLID principles
  2. Write clean, readable code
  3. Test thoroughly
  4. Document decisions
  5. 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

  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 / 3 solved
Implement Repository

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

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

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

Quiz

1. What does extending JpaRepository give you?

Question 1 options

2. How does Spring Data JPA derive queries from method names?

Question 2 options

3. What is a common mistake when implementing Repository?

Question 3 options

Flashcards

Question

What does JpaRepository provide?

Answer

All CRUD operations, pagination, and sorting for free

Question

What is JPQL?

Answer

Java Persistence Query Language — uses entity/field names instead of table/column names

Question

Repository best practices

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