从 QueryDSL 搜索中过滤结果

Filter results from QueryDSL search

我正在使用 QueryDSL 作为 Spring Data Rest 的一部分来搜索我们 API 中的实体。

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

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

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

在使用 Spring 数据 REST 和 QueryDSL 的情况下,要更改查询的标准行为,我们可以使用方面。

例如:默认情况下,我们只需要显示那些 flag 设置为 true:

Model
@Data
@NoArgsConstructor
@Entity
public class Model {

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

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

@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) 的所有调用,如果未设置请求参数 (predicate == null),则将过滤器 model.flag = true 添加到查询中,或者如果它们不包含 'flag' 参数。否则切面不修改原predicate.