I'm trying to implement search functionality limited by IN clause:
I want to implement search implementation with filter limitation:
@GetMapping("find")
public Page<MerchantUserDTO> getAllBySpecification(
@And({
@Spec(path = "name", spec = LikeIgnoreCase.class),
@Spec(path = "login", spec = LikeIgnoreCase.class),
@Spec(path = "email", spec = LikeIgnoreCase.class),
}) Specification<Users> specification,
@SortDefault(sort = "login", direction = Sort.Direction.DESC) Pageable pageable
) {
return merchantUserService.getAllBySpecification(specification, pageable)
.map(g -> MerchantUserDTO.builder()
.id(g.getId())
.login(g.getLogin())
.build()
);
}
@Override
public Page<Users> getAllBySpecification(Specification<Users> specification, Pageable pageable) {
return dao.findAllByTypeIn(specification, pageable, "MerchantUser");
}
Repository:
@Repository
public interface MerchantUserRepository extends JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users> {
Page<Users> findAllByTypeIn(Pageable page, String... types);
Page<Users> findAllByTypeIn(Specification<Users> specification, Pageable pageable, String... types);
}
What is the proper way to extend the specification with IN clause?
specification.and(path.in(types))
path is a attribute but how to implement it properly?
Generally this can be achieved this way:
1) Create specification implementation
2) Use method Page findAll(@Nullable Specification spec, Pageable pageable); inherited from
JpaSpecificationExecutor
interface instead of using your customfindAllByTypeIn(Specification<Users> specification....)
P.S.
With Java 8+ and for simple cases (like yours) the code may be reduced even more. Instead of implementing
Specification<T>
in separate class you can just create a methodUPDATE: Shortest way