Example usage for javax.persistence.criteria Subquery where

List of usage examples for javax.persistence.criteria Subquery where

Introduction

In this page you can find the example usage for javax.persistence.criteria Subquery where.

Prototype

Subquery<T> where(Predicate... restrictions);

Source Link

Document

Modify the subquery to restrict the result according to the conjunction of the specified restriction predicates.

Usage

From source file:com.alliander.osgp.adapter.ws.infra.specifications.JpaDeviceSpecifications.java

@Override
public Specification<Device> forFirmwareModuleVersion(final FirmwareModuleFilterType firmwareModuleFilterType,
        final String firmwareModuleVersion) throws ArgumentNullOrEmptyException {
    if (StringUtils.isEmpty(firmwareModuleVersion)) {
        throw new ArgumentNullOrEmptyException("firmwareModuleVersion");
    }//from  w  ww  .  j  av  a2 s  .c om
    if (firmwareModuleFilterType == null) {
        throw new ArgumentNullOrEmptyException("firmwareModuleType");
    }

    return new Specification<Device>() {
        @Override
        public Predicate toPredicate(final Root<Device> deviceRoot, final CriteriaQuery<?> query,
                final CriteriaBuilder cb) {
            String moduleFieldName = "";
            switch (firmwareModuleFilterType) {
            case COMMUNICATION:
                moduleFieldName = "moduleVersionComm";
                break;
            case FUNCTIONAL:
                moduleFieldName = "moduleVersionFunc";
                break;
            case SECURITY:
                moduleFieldName = "moduleVersionSec";
                break;
            case M_BUS:
                moduleFieldName = "moduleVersionMbus";
                break;
            case MODULE_ACTIVE:
                moduleFieldName = "moduleVersionMa";
                break;
            case ACTIVE_FIRMWARE:
                break;

            default:
                break;
            }

            final Subquery<Long> subquery = query.subquery(Long.class);
            final Root<DeviceFirmware> deviceFirmwareRoot = subquery.from(DeviceFirmware.class);
            subquery.select(deviceFirmwareRoot.get("device").get("id").as(Long.class));
            subquery.where(cb.and(
                    cb.like(cb.upper(deviceFirmwareRoot.get("firmware").<String>get(moduleFieldName)),
                            firmwareModuleVersion.toUpperCase()),
                    cb.equal(deviceFirmwareRoot.<Boolean>get("active"), true)));
            return cb.in(deviceRoot.get("id").as(Long.class)).value(subquery);
        }
    };
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public Page<Order> findPage(Order.Type type, Order.Status status, Member member, Goods goods,
        Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint,
        Boolean isAllocatedStock, Boolean hasExpired, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);//from   ww w  . ja va 2 s.co  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public Long count(Order.Type type, Order.Status status, Member member, Goods goods, Boolean isPendingReceive,
        Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint, Boolean isAllocatedStock,
        Boolean hasExpired) {//  w w w . j  av  a2  s  .c  o  m
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.count(criteriaQuery, null);
}

From source file:net.shopxx.dao.impl.OrderDaoImpl.java

public List<Order> findList(Order.Type type, Order.Status status, Member member, Goods goods,
        Boolean isPendingReceive, Boolean isPendingRefunds, Boolean isUseCouponCode, Boolean isExchangePoint,
        Boolean isAllocatedStock, Boolean hasExpired, Integer count, List<Filter> filters,
        List<net.shopxx.Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
    Root<Order> root = criteriaQuery.from(Order.class);
    criteriaQuery.select(root);//from   w  w w.  j ava  2 s . co  m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (type != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("type"), type));
    }
    if (status != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("status"), status));
    }
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("member"), member));
    }
    if (goods != null) {
        Subquery<Product> productSubquery = criteriaQuery.subquery(Product.class);
        Root<Product> productSubqueryRoot = productSubquery.from(Product.class);
        productSubquery.select(productSubqueryRoot);
        productSubquery.where(criteriaBuilder.equal(productSubqueryRoot.get("goods"), goods));

        Subquery<OrderItem> orderItemSubquery = criteriaQuery.subquery(OrderItem.class);
        Root<OrderItem> orderItemSubqueryRoot = orderItemSubquery.from(OrderItem.class);
        orderItemSubquery.select(orderItemSubqueryRoot);
        orderItemSubquery.where(criteriaBuilder.equal(orderItemSubqueryRoot.get("order"), root),
                criteriaBuilder.in(orderItemSubqueryRoot.get("product")).value(productSubquery));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(orderItemSubquery));
    }
    if (isPendingReceive != null) {
        Predicate predicate = criteriaBuilder.and(
                criteriaBuilder.or(root.get("expire").isNull(),
                        criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())),
                criteriaBuilder.equal(root.get("paymentMethodType"), PaymentMethod.Type.cashOnDelivery),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.completed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.failed),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.canceled),
                criteriaBuilder.notEqual(root.get("status"), Order.Status.denied),
                criteriaBuilder.lessThan(root.<BigDecimal>get("amountPaid"), root.<BigDecimal>get("amount")));
        if (isPendingReceive) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isPendingRefunds != null) {
        Predicate predicate = criteriaBuilder.or(
                criteriaBuilder.and(
                        criteriaBuilder.or(
                                criteriaBuilder.and(root.get("expire").isNotNull(),
                                        criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"),
                                                new Date())),
                                criteriaBuilder.equal(root.get("status"), Order.Status.failed),
                                criteriaBuilder.equal(root.get("status"), Order.Status.canceled),
                                criteriaBuilder.equal(root.get("status"), Order.Status.denied)),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"), BigDecimal.ZERO)),
                criteriaBuilder.and(criteriaBuilder.equal(root.get("status"), Order.Status.completed),
                        criteriaBuilder.greaterThan(root.<BigDecimal>get("amountPaid"),
                                root.<BigDecimal>get("amount"))));
        if (isPendingRefunds) {
            restrictions = criteriaBuilder.and(restrictions, predicate);
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.not(predicate));
        }
    }
    if (isUseCouponCode != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isUseCouponCode"), isUseCouponCode));
    }
    if (isExchangePoint != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isExchangePoint"), isExchangePoint));
    }
    if (isAllocatedStock != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isAllocatedStock"), isAllocatedStock));
    }
    if (hasExpired != null) {
        if (hasExpired) {
            restrictions = criteriaBuilder.and(restrictions, root.get("expire").isNotNull(),
                    criteriaBuilder.lessThanOrEqualTo(root.<Date>get("expire"), new Date()));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(root.get("expire").isNull(),
                    criteriaBuilder.greaterThan(root.<Date>get("expire"), new Date())));
        }
    }
    criteriaQuery.where(restrictions);
    return super.findList(criteriaQuery, null, count, filters, orders);
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void createPredicateResourceId(CriteriaBuilder builder, CriteriaQuery<?> cq,
        List<Predicate> thePredicates, Expression<Long> theExpression) {
    if (myParams.isPersistResults()) {
        if (mySearchEntity.getTotalCount() > -1) {
            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<SearchResult> subQfrom = subQ.from(SearchResult.class);
            subQ.select(subQfrom.get("myResourcePid").as(Long.class));
            Predicate subQname = builder.equal(subQfrom.get("mySearch"), mySearchEntity);
            subQ.where(subQname);

            thePredicates.add(theExpression.in(subQ));
        }/*  w w w  .  jav a  2s.  c  o m*/
    } else {
        if (myPids != null) {
            thePredicates.add(theExpression.in(myPids));
        }
    }

}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateParamMissingResourceLink(String joinName, String theParamName) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<ResourceLink> subQfrom = subQ.from(ResourceLink.class);
    subQ.select(subQfrom.get("mySourceResourcePid").as(Long.class));

    // subQ.where(builder.equal(subQfrom.get("myParamName"), theParamName));
    Predicate path = createResourceLinkPathPredicate(theParamName, subQfrom);
    subQ.where(path);

    List<Predicate> predicates = new ArrayList<Predicate>();
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));

    cq.where(builder.and(toArray(predicates)));

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    List<Long> resultList = q.getResultList();
    doSetPids(new HashSet<Long>(resultList));
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateParamMissing(String joinName, String theParamName,
        Class<? extends BaseResourceIndexedSearchParam> theParamTable) {
    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceTable> from = cq.from(ResourceTable.class);
    cq.select(from.get("myId").as(Long.class));

    Subquery<Long> subQ = cq.subquery(Long.class);
    Root<? extends BaseResourceIndexedSearchParam> subQfrom = subQ.from(theParamTable);
    subQ.select(subQfrom.get("myResourcePid").as(Long.class));
    Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
    Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
    subQ.where(builder.and(subQtype, subQname));

    List<Predicate> predicates = new ArrayList<Predicate>();
    predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
    predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
    predicates.add(builder.isNull(from.get("myDeleted")));
    createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));

    cq.where(builder.and(toArray(predicates)));

    ourLog.info("Adding :missing qualifier for parameter '{}'", theParamName);

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    doSetPids(q.getResultList());//from w  w  w  .ja  v a 2s  .c o  m
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

private void addPredicateTag(List<List<? extends IQueryParameterType>> theList, String theParamName,
        DateRangeParam theLastUpdated) {
    TagTypeEnum tagType;/*from   ww w  .  j  av a 2  s.  co m*/
    if (Constants.PARAM_TAG.equals(theParamName)) {
        tagType = TagTypeEnum.TAG;
    } else if (Constants.PARAM_PROFILE.equals(theParamName)) {
        tagType = TagTypeEnum.PROFILE;
    } else if (Constants.PARAM_SECURITY.equals(theParamName)) {
        tagType = TagTypeEnum.SECURITY_LABEL;
    } else {
        throw new IllegalArgumentException("Param name: " + theParamName); // shouldn't happen
    }

    /*
     * CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<Long> cq =
     * builder.createQuery(Long.class); Root<ResourceTable> from = cq.from(ResourceTable.class);
     * cq.select(from.get("myId").as(Long.class));
     * 
     * Subquery<Long> subQ = cq.subquery(Long.class); Root<? extends BaseResourceIndexedSearchParam> subQfrom =
     * subQ.from(theParamTable); subQ.select(subQfrom.get("myResourcePid").as(Long.class));
     * Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName); Predicate subQtype =
     * builder.equal(subQfrom.get("myResourceType"), myResourceName);
     * subQ.where(builder.and(subQtype, subQname));
     * 
     * List<Predicate> predicates = new ArrayList<Predicate>();
     * predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
     * predicates.add(builder.equal(from.get("myResourceType"),
     * myResourceName)); predicates.add(builder.isNull(from.get("myDeleted"))); createPredicateResourceId(builder, cq,
     * predicates, from.get("myId").as(Long.class));
     */

    List<Pair<String, String>> notTags = Lists.newArrayList();
    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        for (IQueryParameterType nextOrParams : nextAndParams) {
            if (nextOrParams instanceof TokenParam) {
                TokenParam param = (TokenParam) nextOrParams;
                if (param.getModifier() == TokenParamModifier.NOT) {
                    if (isNotBlank(param.getSystem()) || isNotBlank(param.getValue())) {
                        notTags.add(Pair.of(param.getSystem(), param.getValue()));
                    }
                }
            }
        }
    }

    /*
     * We have a parameter of ResourceType?_tag:not=foo This means match resources that don't have the given tag(s)
     */
    if (notTags.isEmpty() == false) {
        // CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
        // CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        // Root<ResourceTable> from = cq.from(ResourceTable.class);
        // cq.select(from.get("myId").as(Long.class));
        //
        // Subquery<Long> subQ = cq.subquery(Long.class);
        // Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
        // subQ.select(subQfrom.get("myResourceId").as(Long.class));
        // Predicate subQname = builder.equal(subQfrom.get("myParamName"), theParamName);
        // Predicate subQtype = builder.equal(subQfrom.get("myResourceType"), myResourceName);
        // subQ.where(builder.and(subQtype, subQname));
        //
        // List<Predicate> predicates = new ArrayList<Predicate>();
        // predicates.add(builder.not(builder.in(from.get("myId")).value(subQ)));
        // predicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        // predicates.add(builder.isNull(from.get("myDeleted")));
        // createPredicateResourceId(builder, cq, predicates, from.get("myId").as(Long.class));
    }

    for (List<? extends IQueryParameterType> nextAndParams : theList) {
        boolean haveTags = false;
        for (IQueryParameterType nextParamUncasted : nextAndParams) {
            if (nextParamUncasted instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                } else if (isNotBlank(nextParam.getSystem())) {
                    throw new InvalidRequestException("Invalid " + theParamName
                            + " parameter (must supply a value/code and not just a system): "
                            + nextParam.getValueAsQueryToken(myContext));
                }
            } else {
                UriParam nextParam = (UriParam) nextParamUncasted;
                if (isNotBlank(nextParam.getValue())) {
                    haveTags = true;
                }
            }
        }
        if (!haveTags) {
            continue;
        }

        CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();

        boolean paramInverted = false;
        List<Pair<String, String>> tokens = Lists.newArrayList();
        for (IQueryParameterType nextOrParams : nextAndParams) {
            String code;
            String system;
            if (nextOrParams instanceof TokenParam) {
                TokenParam nextParam = (TokenParam) nextOrParams;
                code = nextParam.getValue();
                system = nextParam.getSystem();
                if (nextParam.getModifier() == TokenParamModifier.NOT) {
                    paramInverted = true;
                }
            } else {
                UriParam nextParam = (UriParam) nextOrParams;
                code = nextParam.getValue();
                system = null;
            }

            if (isNotBlank(code)) {
                tokens.add(Pair.of(system, code));
            }
        }

        if (tokens.isEmpty()) {
            continue;
        }

        if (paramInverted) {
            ourLog.debug("Searching for _tag:not");

            CriteriaQuery<Long> cq = builder.createQuery(Long.class);
            Root<ResourceTable> newFrom = cq.from(ResourceTable.class);

            Subquery<Long> subQ = cq.subquery(Long.class);
            Root<ResourceTag> subQfrom = subQ.from(ResourceTag.class);
            subQ.select(subQfrom.get("myResourceId").as(Long.class));

            cq.select(newFrom.get("myId").as(Long.class));

            List<Predicate> andPredicates = new ArrayList<Predicate>();
            andPredicates = new ArrayList<Predicate>();
            andPredicates.add(builder.equal(newFrom.get("myResourceType"), myResourceName));
            andPredicates.add(builder.not(builder.in(newFrom.get("myId")).value(subQ)));

            Subquery<Long> defJoin = subQ.subquery(Long.class);
            Root<TagDefinition> defJoinFrom = defJoin.from(TagDefinition.class);
            defJoin.select(defJoinFrom.get("myId").as(Long.class));

            subQ.where(subQfrom.get("myTagId").as(Long.class).in(defJoin));

            List<Predicate> orPredicates = createPredicateTagList(defJoinFrom, builder, tagType, tokens);
            defJoin.where(toArray(orPredicates));

            cq.where(toArray(andPredicates));

            TypedQuery<Long> q = myEntityManager.createQuery(cq);
            Set<Long> pids = new HashSet<Long>(q.getResultList());
            doSetPids(pids);
            continue;
        }

        CriteriaQuery<Long> cq = builder.createQuery(Long.class);
        Root<ResourceTag> from = cq.from(ResourceTag.class);
        List<Predicate> andPredicates = new ArrayList<Predicate>();
        andPredicates.add(builder.equal(from.get("myResourceType"), myResourceName));
        From<ResourceTag, TagDefinition> defJoin = from.join("myTag");

        Join<?, ResourceTable> defJoin2 = from.join("myResource");

        Predicate notDeletedPredicatePrediate = builder.isNull(defJoin2.get("myDeleted"));
        andPredicates.add(notDeletedPredicatePrediate);

        List<Predicate> orPredicates = createPredicateTagList(defJoin, builder, tagType, tokens);
        andPredicates.add(builder.or(toArray(orPredicates)));

        if (theLastUpdated != null) {
            andPredicates.addAll(createLastUpdatedPredicates(theLastUpdated, builder, defJoin2));
        }

        createPredicateResourceId(builder, cq, andPredicates, from.get("myResourceId").as(Long.class));
        Predicate masterCodePredicate = builder.and(toArray(andPredicates));

        cq.select(from.get("myResourceId").as(Long.class));
        cq.where(masterCodePredicate);

        TypedQuery<Long> q = myEntityManager.createQuery(cq);
        Set<Long> pids = new HashSet<Long>(q.getResultList());
        doSetPids(pids);
    }

}

From source file:com.yunguchang.data.ApplicationRepository.java

private Subquery<TBusScheduleCarEntity> applyOverlapScheduleCarSubquery(
        Subquery<TBusScheduleCarEntity> overlapScheduleCarSubQuery, String[] applicationIds,
        Root<TAzCarinfoEntity> carRoot, Root<TRsDriverinfoEntity> driverRoot, CriteriaBuilder cb,
        PrincipalExt principalExt) {/*  w w w.j  a v  a  2 s.  c  om*/
    Root<TBusScheduleCarEntity> subScheduleCarRoot = overlapScheduleCarSubQuery
            .from(TBusScheduleCarEntity.class);
    overlapScheduleCarSubQuery.select(subScheduleCarRoot);

    Path<DateTime> scheduleStartTime = subScheduleCarRoot.get(TBusScheduleCarEntity_.schedule)
            .get(TBusScheduleRelaEntity_.starttime);
    Path<DateTime> scheduleEndTime = subScheduleCarRoot.get(TBusScheduleCarEntity_.schedule)
            .get(TBusScheduleRelaEntity_.endtime);

    DateTime applicationStartTime = null;
    DateTime applicationEndTime = null;
    for (String applicationId : applicationIds) {
        TBusApplyinfoEntity applicationEntity = getApplicationById(applicationId, principalExt);
        if (applicationEntity == null) {
            throw logger.entityNotFound(TBusApplyinfoEntity.class, applicationId);
        }
        if (applicationStartTime == null || applicationEndTime.isAfter(applicationEntity.getBegintime())) {
            applicationStartTime = applicationEntity.getBegintime();
        }
        if (applicationEndTime == null || applicationEndTime.isBefore(applicationEntity.getEndtime())) {
            applicationEndTime = applicationEntity.getEndtime();
        }

    }

    if (applicationStartTime == null || applicationEndTime == null) {
        throw logger.invalidApplication(Arrays.deepToString(applicationIds));
    }

    Predicate predicate = cb.and(
            cb.or(cb.and(cb.between(scheduleStartTime, applicationStartTime, applicationEndTime)),
                    cb.and(cb.between(scheduleEndTime, applicationStartTime, applicationEndTime)),
                    cb.and(cb.lessThan(scheduleStartTime, applicationStartTime),
                            cb.greaterThan(scheduleEndTime, applicationEndTime))),
            subScheduleCarRoot.get(TBusScheduleCarEntity_.status).in(ScheduleStatus.AWAITING.id()));
    if (driverRoot != null) {
        predicate = cb.and(predicate,
                cb.and(cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.car), carRoot),
                        cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.driver), driverRoot)));
    } else {
        predicate = cb.and(predicate, cb.equal(subScheduleCarRoot.get(TBusScheduleCarEntity_.car), carRoot));
    }

    overlapScheduleCarSubQuery.where(predicate);
    return overlapScheduleCarSubQuery;
}

From source file:org.artificer.repository.hibernate.query.ArtificerToHibernateQueryVisitor.java

/**
 * @see org.artificer.common.query.xpath.visitors.XPathVisitor#visit(org.artificer.common.query.xpath.ast.SubartifactSet)
 *///from  w  ww.j  a  va2s. co m
@Override
public void visit(SubartifactSet node) {
    if (node.getFunctionCall() != null) {
        node.getFunctionCall().accept(this);
    } else if (node.getRelationshipPath() != null) {
        From oldRootContext = from;

        if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("relatedDocument")) {
            // derivedFrom
            // TODO: Should this really be LEFT?
            from = from.join("derivedFrom", JoinType.LEFT);

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else if (node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromDocument")
                || node.getRelationshipPath().getRelationshipType().equalsIgnoreCase("expandedFromArchive")) {
            // expandedFrom
            from = from.join("expandedFrom");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }
        } else {
            // Relationship within a predicate.
            // Create a subquery and 'exists' conditional.  The subquery is much easier to handle, later on, if this
            // predicate is negated, as opposed to removing the inner join or messing with left joins.

            List<Predicate> oldPredicates = predicates;
            predicates = new ArrayList<>();

            Subquery relationshipSubquery = query.subquery(ArtificerRelationship.class);
            relationshipFrom = relationshipSubquery.from(ArtificerRelationship.class);
            targetFrom = relationshipFrom.join("targets");
            relationshipSubquery.select(relationshipFrom.get("id"));

            Join relationshipOwnerJoin = relationshipFrom.join("owner");
            predicates.add(criteriaBuilder.equal(relationshipOwnerJoin.get("id"), oldRootContext.get("id")));

            from = relationshipFrom;

            // process constraints on the relationship itself
            node.getRelationshipPath().accept(this);

            // context now needs to be the relationship targets

            from = targetFrom.join("target");

            // Now add any additional predicates included.
            if (node.getPredicate() != null) {
                node.getPredicate().accept(this);
            }

            // Add predicates to subquery
            relationshipSubquery.where(compileAnd(predicates));

            predicates = oldPredicates;

            // Add 'exists' predicate (using subquery) to original list
            predicates.add(criteriaBuilder.exists(relationshipSubquery));
        }

        // restore the original selector (since the relationship was in a predicate, not a path)
        from = oldRootContext;

        if (node.getSubartifactSet() != null) {
            throw new RuntimeException(Messages.i18n.format("XP_MULTILEVEL_SUBARTYSETS_NOT_SUPPORTED"));
        }
    }
}