如何动态拼接 OR 与 AND 条件避免 `Predicate` 数组空指针?

解读

国内一线/二线互联网公司面试时,这道题常被用来区分“只会写 JPA 方法名”与“真正写过复杂查询”的候选人。
空指针的本质是:当没有任何过滤条件时,开发者仍把长度为 0 的 Predicate[] 直接丢给 cb.and() / cb.or(),这两个方法不接受空数组,于是抛出 IllegalArgumentException。
面试官期望你给出可维护、类型安全、无 if-else 嵌套的写法,最好能结合元模型(JPA Metamodel)与泛型工具方法,体现你对 Specification 与 Stream API 的熟练度。

知识点

  1. CriteriaBuilder 的 and/or 变长参数不能为空
  2. Predicate[] 长度为 0 时,应返回 cb.conjunction()(恒真)或 cb.disjunction()(恒假)
  3. Spring Data JPA 的 Specification 接口是动态条件的最佳载体,可链式拼装
  4. **元模型(JPA Static Metamodel)**能在编译期检查字段名,避免魔法字符串
  5. Stream.reduce 可以把 List<Predicate> 安全归约成单个 Predicate,无需判空
  6. 查询热点字段(状态、时间区间、模糊搜索)要兼顾索引失效与绑定参数问题,防止 SQL 注入与全表扫描

答案

下面给出零 if-else、无空指针、同时支持 AND/OR 混合嵌套的通用模板,可直接用在生产代码里,面试时手写出来即可满分。

// 工具类:DynamicSpec.java
public final class DynamicSpec {
    private DynamicSpec() {}

    // 组装 AND 条件
    public static Specification<?> and(List<Specification<?>> specs) {
        return specs.isEmpty() ? (root, query, cb) -> cb.conjunction()
                : specs.stream().reduce(Specification::and).orElseThrow();
    }

    // 组装 OR 条件
    public static Specification<?> or(List<Specification<?>> specs) {
        return specs.isEmpty() ? (root, query, cb) -> cb.disjunction()
                : specs.stream().reduce(Specification::or).orElseThrow();
    }

    // 模糊查询示例,使用元模型防止写错字段
    public static Specification<User> nameLike(String name) {
        return StringUtils.isBlank(name) ? null :
                (root, query, cb) -> cb.like(root.get(User_.name), "%" + name + "%");
    }

    // 状态等值查询
    public static Specification<User> statusEq(Integer status) {
        return status == null ? null :
                (root, query, cb) -> cb.equal(root.get(User_.status), status);
    }
}

// 使用端:Service 层
public Page<User> search(String name, Integer status, Pageable pageable) {
    List<Specification<User>> list = new ArrayList<>();
    Optional.ofNullable(DynamicSpec.nameLike(name)).ifPresent(list::add);
    Optional.ofNullable(DynamicSpec.statusEq(status)).ifPresent(list::add);

    Specification<User> spec = DynamicSpec.and(list);   // 无空指针
    return userRepository.findAll(spec, pageable);
}

关键点解释

  1. 空集合时返回 cb.conjunction(),等价于 1=1,不会触发空指针
  2. Stream.reduce 把 List 归约成单个 Specification,代码量最小
  3. 每个条件先返回 null,再用 Optional 过滤,避免在数组里出现 null 元素
  4. 元模型 User_.name 在编译期检查,重构时字段改名会直接编译失败,杜绝线上事故
  5. 如果业务需要OR 套 AND(例如“(name like ? or phone like ?) and status = ?”),只需再包一层 Specification.where( or(...) ).and( ... ),依旧无嵌套 if

拓展思考

  1. 复杂嵌套场景:当查询树深度 >2 时,用 Specification 会写出链式黑洞,可改用 QueryDSL 的 BooleanBuilder,其 andAnyOf(...) / orAllOf(...) 对集合为空有内置保护,代码可读性更高
  2. 性能陷阱:动态条件里一旦出现 cb.function() 写 MySQL 函数,会导致索引失效;面试时可补充“用虚拟列+函数索引”或“冗余字段”的治理方案
  3. 安全加固:拼接 LIKE 条件时,必须手动转义 % 和 _,否则前端传入“%%%”可造成全表扫描;可封装 EscapeUtils.containsLike(String) 统一处理
  4. 多租户/数据权限:把租户 ID、部门编码等强制条件写成 Hibernate Filter,在 Session 级别自动追加,避免程序员忘记 AND 进去
  5. 云原生扩展:在 Spring Boot 3 + Hibernate 6 中,JPA Specification 与 Spring Data R2DBC 无法混用,可提前准备“迁移到 QueryDSL Kotlin Coroutine”或“直接写 jOOQ”的过渡话术,展示你对技术演进的预判