You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用QuerydslBinderCustomizer为所有字符串多值查询参数配置containsIgnoreCase

解决Querydsl多值字符串参数的大小写不敏感包含查询问题

当使用all方法处理多值参数时,需先将泛型Path<?>强转为StringPath,再为每个参数值生成大小写不敏感的包含条件,最后用逻辑或组合所有条件,即可实现多值参数的匹配需求。

修改后的完整代码如下:

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.querydsl.binding.QuerydslBindings;
import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer;
import org.springframework.data.querydsl.binding.QuerydslPredicateExecutor;
import org.springframework.data.repository.ReadOnlyRepository;

public interface CarRepository extends ReadOnlyRepository<Car, Integer>, QuerydslPredicateExecutor<Car>, QuerydslBinderCustomizer<QCar> {
    
    @Override
    default void customize(QuerydslBindings bindings, QCar car) {
        bindings.bind(String.class).all((path, values) -> {
            // 强转为StringPath(因绑定的是String.class,强转安全)
            StringPath stringPath = (StringPath) path;
            BooleanBuilder predicate = new BooleanBuilder();
            // 为每个参数值生成大小写不敏感包含条件,并用or连接
            for (String value : values) {
                predicate.or(stringPath.containsIgnoreCase(value));
            }
            return Optional.of(predicate);
        });
    }
}

代码说明

  • 类型强转:由于我们绑定的是String.class,所有匹配的路径必然是StringPath类型,因此强转操作是安全的。
  • 条件组合:通过BooleanBuilder遍历所有多值参数,为每个值生成containsIgnoreCase条件,最终用or逻辑组合,确保满足任一参数值的匹配都会被查询命中。
  • 返回值要求:all方法需要返回Optional<Predicate>,将组合好的条件包装后返回即可。

修改后,请求http://my-service/cars?make=toy&make=hond时,会同时匹配品牌包含toy(不区分大小写)和hond(不区分大小写)的车辆,Toyota和Honda都会被查询出来。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:32:35