I want to implement search functionality with several sub conditions. I tried this:
@GetMapping("find")
public Page<PaymentTransactionsDTO> getAllBySpecification(
@And({
@Spec(path = "name", spec = LikeIgnoreCase.class),
@Spec(path = "unique_id", spec = LikeIgnoreCase.class),
@Spec(path = "createdAt", params = "from", spec = GreaterThanOrEqual.class),
@Spec(path = "createdAt", params = "to", spec = LessThanOrEqual.class)
}) Specification<PaymentTransactions> specification,
Pageable pageable
) {
return transactionService.getAllBySpecification(specification, pageable));
}
Repository:
@Override
public Page<PaymentTransactions> getAllBySpecification(final Specification<PaymentTransactions> specification, final Pageable pageable) {
return dao.findAll(specification, pageable);
}
Currently this request is working:
GET /api/transactions/find?unique_id=22&page=0&size=10
But also I want to implement these additional search conditions not only sending basic search for unique_id
:
start with
=
end with
contains
Using https://github.com/tkaczmarzyk/specification-arg-resolver is there some way to send additional sub conditions? I can't find a solution for this issue in general what are the best practices to send these values?
If you want to create your very special filter I believe you should start with invention of your search interface. For example like that:
After that, you will be able to try to implement it.
IMO the best way to solve such a task is to use Spring Data JPA Specifications (and JPA Criteria API). For example:
1) Let's create a
Filter
class that implementsSpecification
for our entityModel
:2) Then create a controller method:
All that's left to do is prepare our predicates ))
To make this, we can create a handy 'Predicate Builder' interface first:
Then try to make our predicates:
equal
like
start with
between
from
to
It remains only to complete the
Filter
class:Of course it's just one example of implementation. You can create your very own implementation of specifications and predicates you need. The main things here are: