我有以下网络服务,可以自动将获取参数查询转换为数据库选择:
public interface PersonRepo extends
JpaRepository<Person, Long>,
QuerydslPredicateExecutor<Person> {
}
@GetMapping
public ResponseEntity getFiltered(
@QuerydslPredicate(root = Person.class) Predicate predicate, Pageable pageable) {
return ResponseEntity.ok(personRepo.findAll(predicate, pageable)));
)
}
可以执行以下查询:
GET /people?name=John&age=18
GET /people?name=John&age=18&page=1&sort=name,desc
问题:我想按如下方式应用比较器查询:
GET /people?name=John&age>18
GET /people?name=John&age>18&age<30
GET /people?name=John&age<30
问题:我怎样才能实现这一目标?至少后面的查询不起作用。
最佳答案
我通过为字段定义占位符并使用QuerydslBinderCustomizer
找到了解决方案:
public interface PersonRepo extends
JpaRepository<Person, Long>,
QuerydslPredicateExecutor<Person>,
QuerydslBinderCustomizer<Person> {
default void customize(final QuerydslBindings bindings, final QPerson person) {
bindings.bind(cache.ageMin).first((path, value) -> person.age.goe(value));
bindings.bind(cache.ageMax).first((path, value) -> person.age.loe(value));
}
}
当然,年龄字段必须作为 transient 字段存在,以便 querydsl 知道它们:
@Entity
class Person {
@Transient
@QueryType(PropertyType.NUMERIC)
public int ageMin;
@Transient
@QueryType(PropertyType.NUMERIC)
private int ageMax;
}
关于java - 如何向 querydsl 谓词添加比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57758403/