I am reading Spring In Action (6th edition) to get myself into learning the Spring framework and I have a doubt about how to override the default behavior of Spring JPA when declaring repositories.
As far as I have read so far, I can declare repository methods such as findByName()
and let Spring magically implement the method. Now, let's imagine that the records in the repository have a boolean column named enabled
, and I want the application to only process the records with enabled = TRUE
. I know I could declare methods such as findByNameAndEnabledIsTrue()
but I wonder whether there is a way to make, for example, findByName()
take into account this flag.
So far I tried to override the method, but it doesn't seem to work, since there's actual no method defined at compile time:
@Override
List<Customer> findByName(@Param("name") String name) {
return findByNameAndEnabledIsTrue(name);
}
How could this be done?
Thank you.
The simplest way is to use @Query
to explicitly define the query using JPQL rather than relies on spring-data to generate the query based on the query method name. In this way, you can get back the total control to define what the query you exactly want to have . Something like :
public interface CustomerRepository extends JpaRepository<Customer, Long> {
@Query("select u from Customer c where c.name = :name and c.enabled = true")
List<Customer> findByName(@Param("name") String name);
}
This is the way I prefer. Simple, flexible and much less magic.
If you insist do not want to write JPQL, you can implement a custom repository (See this) , and inject the CustomerRepository
into this custom repository and reuse it method. Something like :
interface CustomerRepository extends JpaRepository<Customer, Long> , CustomizedCustomerRepository {
List<Customer> findByNameAndEnabledIsTrue();
}
interface CustomizedCustomerRepository {
void findByName(String name);
}
class CustomizedCustomerRepositoryImpl implements CustomizedCustomerRepository {
@Autowired
private CustomerRepository repo;
@Override
List<Customer> findByName(String name) {
return repo.findByNameAndEnabledIsTrue(name);
}
}