Reputation: 1109
Spring Data allows you to declare methods like findByLastname() in your repository interface and it generates the queries from the method name automatically for you.
Is it possible to somehow have these automatically-generated queries also accept a Specification, so that additional restrictions can be made on the data before it's returned?
That way, I could for example call findByLastname("Ted", isGovernmentWorker()), which would find all users that have the last name Ted AND who satisfy the isGovernmentWorker() specification.
I need this because I'd like the automated query creation provided by Spring Data and because I still need to be able to apply arbitrary specifications at runtime.
Upvotes: 4
Views: 6661
Reputation: 4134
There is no such feature. Specifications can only be applied on JpaSpecificationExecutor operations.
Update The data access operations are generated by a proxy. Thus if we want to group the operations (as in findByName + Criteria) in a single SELECT call, the proxy must understand and support this kind of usage; which it does not.
The intended usage, when employing Specification API would look like this for your case:
findAll(Specifications.where(hasLastName("Ted")).and(isGovernmentWorker())
Upvotes: 4
Reputation: 9319
Spring data allows you to implement custom repository and use Specifications or QueryDSL.
Please see this article.
So at the end you will have one YourCustomerRepository
and appropriate YourRepositoryImpl
implementation, where you will put your findByLastname("Ted", isGovernmentWorker())
method.
And then YourRepository
should extend YourCustomerRepository
interface.
Upvotes: 0