Spring Data JPA Basics
BeginnerSpring Data JPA generates repository implementations at runtime, eliminating boilerplate DAO code for standard CRUD and derived-query operations.
Overview
Spring Data JPA is the Spring project that removes boilerplate DAO code for database access. You define an interface that extends JpaRepository<Entity, ID> and Spring generates the implementation at runtime using JDK proxies. Out of the box you get save(), findById(), findAll(), delete(), and pagination. Beyond that, Spring Data parses method names like findByEmailAndStatus() and generates the corresponding JPQL query — no SQL or @Query needed. For complex queries, @Query accepts JPQL or native SQL. Spring Data JPA sits on top of JPA / Hibernate — you still configure a DataSource and EntityManagerFactory, but Spring Boot auto-configures those from application.yml.
JpaRepository — Built-in Methods
JpaRepository extends PagingAndSortingRepository, which extends CrudRepository. The hierarchy gives you: - **CrudRepository**: save, findById, existsById, findAll(Iterable<ID>), count, deleteById, delete - **PagingAndSortingRepository**: findAll(Pageable), findAll(Sort) - **JpaRepository** adds: saveAll, flush, saveAndFlush, deleteAllInBatch, getReferenceById
spring-boot-starter-data-jpa auto-configures DataSource, EntityManagerFactory, and JpaTransactionManager from your application.yml properties.
// 1. Entity
@Entity
@Table(name = "orders")
public class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String reference;
private String status;
@Column(name = "customer_id")
private Long customerId;
private BigDecimal total;
private LocalDateTime createdAt;
// getters / setters
}
// 2. Repository — just an interface, Spring provides the implementation
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
// built-in: save, findById, findAll, delete, count, existsById, etc.
}
// 3. Service — inject and use
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepo;
public Order create(Order order) {
return orderRepo.save(order); // INSERT
}
public Optional<Order> find(Long id) {
return orderRepo.findById(id); // SELECT … WHERE id=?
}
public Page<Order> list(Pageable page) {
return orderRepo.findAll(page); // SELECT with LIMIT/OFFSET
}
}Derived Query Methods
Spring Data parses the method name and generates JPQL automatically. The method name is split into a subject (findBy, countBy, existsBy, deleteBy) and predicates built from field names joined by And/Or. Supported keywords include: Is, Equals, Between, LessThan, GreaterThan, Like, Containing, StartingWith, In, Not, IsNull, IsNotNull, OrderBy.
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
// SELECT … WHERE status = ?
List<Order> findByStatus(String status);
// SELECT … WHERE customer_id = ? AND status = ?
List<Order> findByCustomerIdAndStatus(Long customerId, String status);
// SELECT … WHERE created_at BETWEEN ? AND ?
List<Order> findByCreatedAtBetween(LocalDateTime from, LocalDateTime to);
// SELECT … WHERE total > ? ORDER BY created_at DESC
List<Order> findByTotalGreaterThanOrderByCreatedAtDesc(BigDecimal minTotal);
// SELECT … WHERE status IN (…)
List<Order> findByStatusIn(List<String> statuses);
// SELECT COUNT … WHERE customer_id = ?
long countByCustomerId(Long customerId);
// Pagination: SELECT … WHERE status = ? LIMIT ? OFFSET ?
Page<Order> findByStatus(String status, Pageable pageable);
// EXISTS query
boolean existsByReference(String reference);
}@Query — Custom JPQL and Native SQL
When derived method names become unwieldy or you need features JPQL does not express (DB-specific functions, CTEs), use @Query. @Modifying + @Transactional enables bulk UPDATE and DELETE. Use nativeQuery=true for raw SQL when needed.
@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
// JPQL — entity and field names, not table/column names
@Query("SELECT o FROM Order o WHERE o.customerId = :cid AND o.total > :min")
List<Order> findExpensiveByCustomer(@Param("cid") Long customerId,
@Param("min") BigDecimal minTotal);
// Projection — returns only specific columns as interface
@Query("SELECT o.id AS id, o.reference AS reference FROM Order o WHERE o.status = :status")
List<OrderSummary> findSummariesByStatus(@Param("status") String status);
// Bulk UPDATE — needs @Modifying + @Transactional
@Modifying
@Transactional
@Query("UPDATE Order o SET o.status = :status WHERE o.customerId = :cid")
int updateStatusByCustomer(@Param("status") String status, @Param("cid") Long cid);
// Native SQL — raw MySQL
@Query(value = "SELECT * FROM orders WHERE MATCH(reference) AGAINST (:term IN BOOLEAN MODE)",
nativeQuery = true)
List<Order> fullTextSearch(@Param("term") String term);
}
// Projection interface
public interface OrderSummary {
Long getId();
String getReference();
}Key Points to Remember
- 1Extend JpaRepository<Entity, ID> — Spring generates the implementation at runtime. No @Autowired implementation class needed.
- 2Derived query methods: Spring parses findByFieldAnd/Or/Between/In/Like… and generates the JPQL — no @Query needed for simple queries.
- 3@Query accepts JPQL (entity/field names) or native SQL (nativeQuery=true) for complex queries.
- 4@Modifying + @Transactional is required for @Query UPDATE and DELETE — without them Spring throws an exception.
- 5Return Page<T> by adding a Pageable parameter to any query method — Spring Data handles the COUNT query automatically.
- 6Projection interfaces (with getX() methods matching JPQL aliases) avoid loading full entities for read-only summary queries.
Interview Questions
Sign in to ask AriaWhat is Spring Data JPA and what problem does it solve?
What is the difference between CrudRepository and JpaRepository?
How does Spring Data generate JPQL from a method name like findByEmailAndStatus?
When would you use @Query instead of derived query methods?
How do you implement a repository method that updates records in bulk without loading them into memory?
Ask Aria about Spring Data JPA Basics
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.