简体   繁体   English

排除多个条件的标准生成器

[英]Criteria Builder to exclude multiple conditions

I have a sql query like below我有一个 sql 查询,如下所示

select * from enquiry where NOT(request_type = 'SELF_SERVICE' and enquiry_status_id = 19);

My criteria query builder is like below我的条件查询生成器如下

        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Enquiry> query = cb.createQuery(Enquiry.class);
        Root<Enquiry> enquiryRoot = query.from(Enquiry.class);

        List<Predicate> predicates = new ArrayList<>();
        
        List<Predicate> predicates3 = new ArrayList<>();
        Predicate predicate3 = cb.equal(enquiryRoot.get("requestType"), "SELF_SERVICE");
        Predicate predicate4 = cb.notEqual(enquiryRoot.get("status").get("id"), 19);
        predicates3.add(cb.and(predicate3, predicate4));
        
        predicates.add(cb.and(predicates3.toArray(new Predicate[0])));
        query.where(cb.and(predicates.toArray(new Predicate[0])));

Is there any way to exclude the condition like sql query above?有没有办法排除上面的 sql 查询之类的条件?

Kindly advice.好心劝告。 Thanks.谢谢。

There is CriteriaBuilder.not .CriteriaBuilder.not I think the following maps nicely to your SQL;我认为以下内容很好地映射到您的 SQL; note that the criteria code you have shown probably does not do what you want.请注意,您显示的标准代码可能无法满足您的要求。

So the desired SQL:所以想要的 SQL:

select * from enquiry
where NOT(request_type = 'SELF_SERVICE' and enquiry_status_id = 19);

Maps to this criteria API code:映射到此标准 API 代码:

query
    .select(enquiryRoot)
    .where(
        cb.not(
                cb.and(
                        cb.equal(enquiryRoot.get("requestType"), "SELF_SERVICE"),
                        cb.equal(enquiryRoot.get("status").get("id"), 19)
                )
        )
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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