Java 多列“;或;Spring中的数据使用QueryDsl进行Rest
Spring(Boot)datarest和QueryDsl是否可以跨多个列执行“或”搜索?我已经自定义了绑定,以便在同一搜索路径多次出现时执行“或”搜索(多值绑定)Java 多列“;或;Spring中的数据使用QueryDsl进行Rest,java,spring-boot,spring-data,spring-data-rest,querydsl,Java,Spring Boot,Spring Data,Spring Data Rest,Querydsl,Spring(Boot)datarest和QueryDsl是否可以跨多个列执行“或”搜索?我已经自定义了绑定,以便在同一搜索路径多次出现时执行“或”搜索(多值绑定)myentity?name=foo&name=bar将返回name属性包含foo或bar的所有实体 @Entity MyEntity { @Id Long id; String name; String email; } @RepositoryRestResource(path = "myentity
myentity?name=foo&name=bar
将返回name属性包含foo
或bar
的所有实体
@Entity
MyEntity {
@Id
Long id;
String name;
String email;
}
@RepositoryRestResource(path = "myentity")
public interface MyEntityRepository extends CrudRepository<MyEntity, Long>, ,
QuerydslPredicateExecutor<MyEntity>, QuerydslBinderCustomizer<QMyEntity> {
@Override
default void customize(QuerydslBindings bindings, QMyEntity root) {
bindings.bind(root.id).first(NumberExpression::eq);
bindings.bind(String.class).all((StringPath path, Collection<? extends String> values) -> {
BooleanBuilder predicate = new BooleanBuilder();
values.forEach(value -> predicate.or(path.containsIgnoreCase(value)));
return Optional.of(predicate);
});
}
}
@实体
MyEntity{
@身份证
长id;
字符串名;
字符串电子邮件;
}
@RepositoryRestResource(path=“myentity”)
公共接口MyEntityRepository扩展了Crudepository,
QuerydslPredicateExecutor,QuerydslBinderCustomizer{
@凌驾
默认的void自定义(QuerydslBindings绑定,QMyEntity根){
bindings.bind(root.id).first(NumberExpression::eq);
bindings.bind(String.class).all((StringPath路径,集合尝试使用以下实现:
@Override
default void customize(QuerydslBindings bindings, QDocument root) {
StringPath[] multiPropertySearchPaths = new StringPath[] {root.prop1, root.prop2, root.prop3};
/**
* Binds prop1, prop2 and prop3 in OR clause
* This binding will activate when one of the given properties are searched in query params
*/
bindings.bind(multiPropertySearchPaths).all(new MultiValueBinding<StringPath, String>() {
@Override
public Predicate bind(StringPath path, Collection<? extends String> values) {
BooleanBuilder predicate = new BooleanBuilder();
// Bind paths present in array multiPropertySearchPaths with incoming values
for (StringPath propertyPath : multiPropertySearchPaths) {
values.forEach(value -> predicate.or(propertyPath.containsIgnoreCase(value)));
}
return predicate;
}
});
}
您可以使用此库:
它将允许您运行搜索查询,例如:
/搜索?过滤器=平均值(评级)4.5和品牌名(“奥迪”、“路虎”)和(年份<2018或公里我已经定制了我的绑定,以便“或”当同一搜索路径多次出现时,将执行搜索。顺便说一句,这应该是默认行为,不需要任何绑定自定义。@AlanHay谢谢您提供的信息,我在阅读文档时错过了这一点。只有当您需要不同于equals的表达式时,才需要绑定自定义(如我的示例中的containsIgnoreCase)。感谢您的努力,但这并不能解决我的问题:像document?prop1=valueProp1&prop2=valueProp2
这样的请求将生成一个SQL查询,该查询将搜索所有多属性搜索路径中提交的所有值。因此,它将在“valueProp1”出现在document.prop2
中。我需要的是一个where子句,如where lower(document.prop1)如“valueProp1”,或lower(document.prop2)如“valueProp2”
select * from document
where
lower(document.prop1) like ?1
or lower(document.prop2) like ?1
or lower(document.prop3) like ?1