本文介绍了过滤来自 QueryDSL 搜索的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 QueryDSL 作为 Spring Data Rest 的一部分从我们的 API 搜索实体.

I'm using QueryDSL as part of Spring Data Rest to search entities from our API.

是否可以以某种方式过滤搜索 API,以便默认情况下它不会找到例如停用"的 Car 实体?

Is it possible to somehow filter the search API, so that by default it won't find for example Car entities that are "deactivated"?

目前我在汽车实体上有一个标志,当它设置为 true 时,它​​不应该通过我们的搜索 API 公开,并且设置了这个属性的汽车应该从搜索中排除.

Currently I've a flag on car entity that when it's set to true, it shouldn't be exposed through our search API, and the cars that have this property set should be left out from search.

https://docs.spring.io/spring-data/jpa/docs/1.9.0.RELEASE/reference/html/#core.web.type-safe

推荐答案

如果使用 Spring Data REST 和 QueryDSL,我们可以使用方面来改变查询的标准行为.

In case of using Spring Data REST and QueryDSL, to change standard behavior of queries we can use aspects.

例如:我们需要默认只显示那些flag设置为trueModel:

For example: we need to show by default only those Models whose flag is set to true:

@Data
@NoArgsConstructor
@Entity
public class Model {

    @Id @GeneratedValue private Integer id;
    @NotBlank private String name;
    private boolean flag;
}

在这种情况下,我们像这样实现方面:

In this case we implement the aspect like this:

@Aspect
@Component
public class ModelRepoAspect {

  @Pointcut("execution(* com.example.ModelRepo.findAll(com.querydsl.core.types.Predicate, org.springframework.data.domain.Pageable))")
  public void modelFindAllWithPredicateAndPageable() {
  }

  @Around("modelFindAllWithPredicateAndPageable()")
  public Object filterModelsByFlag(final ProceedingJoinPoint pjp) throws Throwable {

    Object[] args = pjp.getArgs();
    Predicate predicate = (Predicate) args[0];

    BooleanExpression flagIsTrue = QModel.model.flag.eq(true);

    if (predicate == null) {
        args[0] = flagIsTrue;
    } else {
        if (!predicate.toString().contains("model.flag")) {
            args[0] = flagIsTrue.and(predicate);
        }
    }

    return pjp.proceed(args);
  }
}

这个切面拦截了我们repo的findAll(Predicate predicate, Pageable pageable)方法的所有调用,并在查询中添加过滤器model.flag = true,如果请求参数未设置(predicate == null),或者它们不包含flag"参数.否则方面不会修改原始谓词.

This aspect intercepts all calls of method findAll(Predicate predicate, Pageable pageable) of our repo, and add the filter model.flag = true to the query if the request parameters was not set (predicate == null), or if they don't contain 'flag' parameter. Otherwise aspect does not modify original predicate.

这篇关于过滤来自 QueryDSL 搜索的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 10:50