我使用 QueryDSL 作为 Spring Data Rest 的一部分来从我们的 API 中搜索实体。
是否可以以某种方式过滤搜索 API,以便默认情况下不会找到“已停用”的汽车实体?
目前,我在汽车实体上有一个标志,当它设置为 true 时,它不应该通过我们的搜索 API 公开,并且设置了此属性的汽车应该从搜索中排除。
https://docs.spring.io/spring-data/jpa/docs/1.9.0.RELEASE/reference/html/#core.web.type-safe https://docs.spring.io/spring-data/jpa/docs/1.9.0.RELEASE/reference/html/#core.web.type-safe
在使用 Spring Data REST 和 QueryDSL 的情况下,要更改查询的标准行为,我们可以使用方面。
例如:我们需要默认只显示那些Model
s whose flag
被设定为true
:
@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);
}
}
该方面拦截所有方法的调用findAll(Predicate predicate, Pageable pageable)
我们的存储库,并添加过滤器model.flag = true
如果未设置请求参数(predicate == null
),或者如果它们不包含“flag”参数。否则方面不会修改原始内容predicate
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)