Add WHERE IN clause to JPA Specification

青春壹個敷衍的年華 提交于 2019-12-25 01:37:40

问题


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?


回答1:


Generally this can be achieved this way:

1) Create specification implementation

public class MerchantUserSpecification implements Specification<Users> {

    private final List<String> types;

    public MerchantUserSpecification(List<String> types) {
        this.types = types;
    }

    @Override
    public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        if (types != null && !types.isEmpty()) {
            return root.get(Users_.type).in(types);
        } else {
            // always-true predicate, means that no filtering would be applied
            return cb.and(); 
        }
    }

2) Use method Page findAll(@Nullable Specification spec, Pageable pageable); inherited from JpaSpecificationExecutor interface instead of using your custom findAllByTypeIn(Specification<Users> specification....)

@Override
public Page<Users> getAllBySpecification(Specification<Users> specification, Pageable pageable) {
    // combine original specification (passed from outside) and filter-by-types specification
    Specification<Users> finalSpec = specification
           .and(new MerchantUserSpecification(Arrays.asList("MerchantUser")))
    return dao.findAll(finalSpec, pageable)
}

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 method

private Specification<Users> typeIn(List<String> types) {
    return (root, query, cb) -> {
        if (types != null && !types.isEmpty()) {
           return root.get(Users_.type).in(types);
        } else {
           // always-true predicate, means that no filtering would be applied
           return cb.and(); 
        }
    }
}

@Override
public Page<Users> getAllBySpecification(Specification<Users> specification, Pageable pageable) {
    // combine original specification (passed from outside) and filter-by-types specification
    Specification<Users> finalSpec = specification
            .and(typeIn(Arrays.asList("MerchantUser")))
    return dao.findAll(finalSpec, pageable)
}

UPDATE: Shortest way

@Override
public Page<Users> getAllBySpecification(Specification<Users> specification, Pageable pageable) {
    // combine original specification (passed from outside) and filter-by-types specification
    Specification<Users> finalSpec = specification
            .and((root, query, cb) -> root.get(Users_.type).in(Arrays.asList("MerchantUser"))
    return dao.findAll(finalSpec, pageable)
}


来源:https://stackoverflow.com/questions/56948257/implement-specification-with-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!