Query Methods
Explore derived and custom query methods of the Spring Data repositories.
Query methods in Spring Data
Every repository method, when invoked, usually runs a query on the underlying database. Let’s look at different ways of running a data access query on the database using Spring Data repositories.
Derived query methods
Spring Data comes with a query builder mechanism that helps us generate derived query methods using keywords, like FirstBy
, OrderBy
, and Distinct
acting as the subject and And
, Or
, and OrderBy
as the predicate, to set conditions on the properties of a POJO.
Press + to interact
package com.smartdiscover.repository;import com.smartdiscover.entity.Customer;import com.smartdiscover.entity.projection.CustomerFullName;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.CrudRepository;import org.springframework.stereotype.Repository;import java.util.List;import java.util.Optional;import java.util.stream.Stream;@Repositorypublic interface CustomerRepository extends CrudRepository<Customer, Long> {List<Customer> findAllByFirstName(String firstName);Optional<Customer> findFirstByLastNameOrderByFirstNameDesc(String lastName);Customer findFirstByOrderByFirstNameAsc();Stream<Customer> readAllByOrderByIdDesc();}
Explanation:
- Line 16: We declare a method to fetch and return a list of customer objects that match the first name passed