如何使用Spring Specification消除代码中的重复项?

时间:2019-06-13 12:25:37

标签: java spring spring-data

我需要创建Spring规范,以便使用ANR和OR条件通过多个字段进行搜索。但是我还需要通过另一个字段DESC命令查询。构建这样的表达式时,我在每个子表达式中都使用ORDER BY。如何消除重复?

query.orderBy(cb.desc(root.get(ExternalPatientEntity_.dateCreated)));

            return cb.and(predicates.build().toArray(new Predicate[0])); 

在单个表达式中,但是我需要结合AND和OR,所以这没有用。

    private static Specification<PatientEntity> getPatientById(PatientsSearchParameters searchParameters) {
        return (root, query, cb) -> {
            Predicate predicate = null;
            if (searchParameters.getId() != null) {
                predicate = cb.equal(root.get(PatientEntity_.clinId), searchParameters.getId());
            }
            query.orderBy(cb.desc(root.get(PatientEntity_.dateCreated)));
            return predicate;
        };
    }

    private static Specification<PatientEntity> getPatientByAnotherId(PatientsSearchParameters searchParameters) {
        return (root, query, cb) -> {
            Predicate predicate = null;
            if (searchParameters.getAnotherId() != null) {
                predicate = cb.equal(root.get(PatientEntity_.clinId), searchParameters.getAnotherId());
            }
            query.orderBy(cb.desc(root.get(PatientEntity_.dateCreated)));
            return predicate;
        };
    }

    private static Specification<PatientEntity> getPatientByIsAdmin(PatientsSearchParameters searchParameters) {
        return (root, query, cb) -> {
            Predicate predicate = null;
            if (searchParameters.getIdsId() != null) {
                predicate = cb.isNull(root.get(PatientEntity_.dateArchived));
            }
            query.orderBy(cb.desc(root.get(PatientEntity_.dateCreated)));
            return predicate;
        };
    }

    public static Specification<PatientEntity> search(PatientsSearchParameters searchParameters) {
        return Specifications.where(getPatientById(searchParameters))
                .and(getPatientByAnotherId(searchParameters))
                .or(getPatientByIsAdmin(searchParameters));
    }

0 个答案:

没有答案