Spring Data JPA Repositories and Queries
Spring Data JPA generates repository implementations from interfaces. You should know derived query methods, @Query, projections, pagination, Specifications and auditing, and the limits of each.
What you will learn
- Use CrudRepository, JpaRepository and derived queries
- Write JPQL and native queries with @Query and @Modifying
- Paginate and sort with Pageable
- Build dynamic filters with Specifications
Key concepts
Derived queries
Method names become queries: findByEmailIgnoreCase, findTop10ByStatusOrderByCreatedAtDesc, existsByEmail, countByStatus.
@Query
JPQL by default, or nativeQuery = true for SQL. Updates and deletes need @Modifying (and a transaction).
Page vs Slice
Page runs an extra COUNT query to know the total pages. Slice only knows whether there is a next page, which is cheaper for infinite scroll.
Specifications
Composable criteria for dynamic search screens: where(hasStatus(s)).and(createdAfter(d)).
Step by step
A repository
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
Optional<User> findByEmailIgnoreCase(String email);
boolean existsByEmail(String email);
Slice<User> findByCityOrderByCreatedAtDesc(String city, Pageable pageable);
@Modifying
@Query("update User u set u.active = false where u.lastLoginAt < :before")
int deactivateInactive(Instant before);
interface NameOnly { String getName(); String getEmail(); } // interface projection
List<NameOnly> findByActiveTrue();
}Examples
Auditing created and updated times
@EnableJpaAuditing // on a @Configuration class
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
@CreatedDate private Instant createdAt;
@LastModifiedDate private Instant updatedAt;
@CreatedBy private String createdBy; // needs an AuditorAware bean
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Build a search endpoint with optional filters (city, status, date range) using Specifications.
- Explain why a @Modifying query does not update entities already in the persistence context, and fix it with clearAutomatically.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
CrudRepository vs JpaRepository?
CrudRepository gives basic CRUD. ListCrudRepository returns Lists. PagingAndSortingRepository adds paging and sorting. JpaRepository adds JPA-specific methods such as flush, saveAllAndFlush, deleteAllInBatch and getReferenceById.
findById vs getReferenceById?
findById queries the database and returns Optional. getReferenceById returns a lazy proxy without a query, useful to set a foreign key (order.setCustomer(ref)); accessing its fields later hits the database and throws if the row does not exist.
Summary
Use derived queries for simple lookups, @Query and projections for specific reads, Slice for infinite scroll, Specifications for dynamic filters, and auditing for timestamps.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus