Skip to content

Conversation

shaykeren
Copy link

Problem

Critical N+1 query performance issue detected in the /vets.html endpoint causing 5 repeated database queries per request.

Issue ID: e8efc2b4-5f5e-11f0-bbd9-0242ac160009
Affected Endpoint: HTTP GET /vets.html
Service: spring-petclinic
Trace ID: E78ADC1B4AB172AAA6DAC2D716CB4E0D

Solution

Implemented eager fetching with JOIN FETCH to resolve the N+1 query pattern by:

1. VetRepository Changes

  • Added findAllWithSpecialties() method with @Query("SELECT v FROM Vet v LEFT JOIN FETCH v.specialties")
  • Added paginated version findAllWithSpecialties(Pageable pageable) for the HTML endpoint
  • Both methods use @Transactional(readOnly = true) and @Cacheable("vets") to maintain existing behavior

2. VetController Changes

  • Updated findPaginated() method to use findAllWithSpecialties(pageable) instead of findAll(pageable)
  • Updated showResourcesVetList() method to use findAllWithSpecialties() instead of findAll()

Impact

  • Resolves N+1 query issue by fetching vets and their specialties in a single query
  • Maintains existing functionality including pagination and caching
  • Preserves all existing method signatures and behavior
  • Minimal code changes focused only on the specific performance issue

Testing

The changes maintain backward compatibility and preserve all existing functionality while optimizing database queries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant