简体   繁体   中英

Combining JPA And/Or Criteria Predicates

I want to query like: (sku = 'A' AND uom_code = 'B') OR (sku = C' AND uom_code = 'D')

But my predicate generate such as (sku = 'A' AND uom_code = 'B' OR sku = 'C' AND uom_code = 'D')

how to fix it. Thank you.

public class VariantSpecification implements Specification<VariantModel> {

private final VariantFilter filter;

public VariantSpecification(VariantFilter filter) {
    this.filter = filter;
}

@Override
public Predicate toPredicate(
    Root<VariantModel> root,
    CriteriaQuery<?> query,
    CriteriaBuilder cb
) {
    final List<Predicate> predicates = new ArrayList<>();

    if (filter.getMerchantId() != null) {
        predicates.add(cb.equal(root.get("merchantId"), filter.getMerchantId()));
    }

    Predicate predicate = cb.and(predicates.toArray(new Predicate[0]));

    List<Predicate> predicatesMap = new ArrayList<>();
    if (!CollectionUtils.isEmpty(filter.getSkusUoms())) {
        filter.getSkusUoms().forEach(pair -> {
            String sku = pair.getLeft();
            String uom = pair.getRight();
            Predicate predicateSku = cb.equal(root.get("sku"), sku);
            Predicate predicateUom = cb.equal(root.get("uomCode"), uom);
            predicatesMap.add(cb.or(cb.and(predicateSku, predicateUom)));
        });
    }
 
    if (!predicatesMap.isEmpty()) {
        Predicate predicateSector = cb.or(predicatesMap.toArray(new Predicate[0]));
        return cb.and(predicate, predicateSector);
    }
    return predicate;
}

}

Yeah my mistake,

SELECT ... FROM ... WHERE (expression1 AND expression2) OR (expression3 AND expression4)



SELECT ... FROM ... WHERE expression1 AND expression2 OR expression3 AND expression4



According to the SQL specification, both statements mean the same thing. It doesn't matter whether the statement contains the () or not, so Hibernate doesn't use them. The order of precedence is like this, similar to 1+2*3 is the same as 1+(2*3).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM