Example usage for javax.persistence.criteria Path get

List of usage examples for javax.persistence.criteria Path get

Introduction

In this page you can find the example usage for javax.persistence.criteria Path get.

Prototype

<Y> Path<Y> get(String attributeName);

Source Link

Document

Create a path corresponding to the referenced attribute.

Usage

From source file:org.agric.oxm.utils.JpaUtils.java

/**
 * Gets a Path from Path using property path
 * //from   w  w  w. j  a va 2s  .  co  m
 * @param path
 *            the base path
 * @param propertyPath
 *            property path String like "customer.order.price"
 * @return a new Path for property
 */
public static Path<?> getPath(Path<?> path, String propertyPath) {
    if (StringUtils.isEmpty(propertyPath))
        return path;

    String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
    Path<?> p = path.get(name);

    return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));

}

From source file:org.apache.ambari.server.api.query.JpaSortBuilder.java

/**
 * Builds the list of sort orders based on the supplied request and JPA
 * predicate visitor.//from w ww  .  j av  a2  s  .  c om
 *
 * @param sortRequests
 *          the Ambari sort request properties to turn into a JPA sort
 *          request. If {@code null} or the {@link SortRequestProperty} list
 *          is null, an empty list is returned.
 * @param visitor
 *          a visitor that knows how to convert the Ambari properties into
 *          {@link SingularAttribute} (not {@code null}).
 * @return a list of sorts or an empty list if none (never {@code null}).
 */
public List<Order> buildSortOrders(SortRequest sortRequest, JpaPredicateVisitor<T> visitor) {

    if (null == sortRequest || null == sortRequest.getProperties()) {
        return Collections.emptyList();
    }

    CriteriaBuilder builder = visitor.getCriteriaBuilder();
    List<SortRequestProperty> sortProperties = sortRequest.getProperties();
    List<Order> sortOrders = new ArrayList<Order>(sortProperties.size());

    for (SortRequestProperty sort : sortProperties) {
        String propertyId = sort.getPropertyId();

        List<? extends SingularAttribute<?, ?>> singularAttributes = visitor.getPredicateMapping(propertyId);

        if (null == singularAttributes || singularAttributes.size() == 0) {
            continue;
        }

        Path<?> path = null;
        for (SingularAttribute<?, ?> singularAttribute : singularAttributes) {
            if (null == path) {

                CriteriaQuery<T> query = visitor.getCriteriaQuery();
                Set<Root<?>> roots = query.getRoots();

                // if there are existing roots; use the existing roots to prevent more
                // roots from being added potentially causing a cartesian product
                // where we don't want one
                if (null != roots && !roots.isEmpty()) {
                    Iterator<Root<?>> iterator = roots.iterator();
                    while (iterator.hasNext()) {
                        Root<?> root = iterator.next();

                        Class<?> visitorEntityClass = visitor.getEntityClass();
                        if (ObjectUtils.equals(visitorEntityClass, root.getJavaType())
                                || ObjectUtils.equals(visitorEntityClass, root.getModel().getJavaType())) {
                            path = root.get(singularAttribute.getName());
                            break;
                        }
                    }
                }

                // no roots exist already which match this entity class, create a new
                // path
                if (null == path) {
                    path = query.from(visitor.getEntityClass()).get(singularAttribute.getName());
                }
            } else {
                path = path.get(singularAttribute.getName());
            }
        }

        Order sortOrder = null;
        if (sort.getOrder() == org.apache.ambari.server.controller.spi.SortRequest.Order.ASC) {
            sortOrder = builder.asc(path);
        } else {
            sortOrder = builder.desc(path);
        }

        sortOrders.add(sortOrder);
    }

    return sortOrders;
}

From source file:org.apache.cxf.jaxrs.ext.search.jpa.AbstractJPATypedQueryVisitor.java

private Path<?> getNextPath(Path<?> element, String name, ClassValue cv, CollectionCheckInfo collSize) {
    if (collSize == null && (cv.isCollection(name) || isJoinProperty(name))
            && (element == root || element instanceof Join)) {
        return element == root ? root.join(name) : ((Join<?, ?>) element).join(name);
    } else {//from w  w w.ja v  a  2 s .c  om
        return element.get(name);
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * @since 5.0/*from  ww  w .j av  a  2s. c  om*/
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return Set of ratings per portlet definition
 */
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public Set<IMarketplaceRating> getRatingsByFname(String fname) {

    //Build criteria to fetch MarketplaceRatingImpl based on the incoming portlet name. 
    final EntityManager entityManager = this.getEntityManager();
    final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    final CriteriaQuery<IMarketplaceRating> getByPortlet = cb.createQuery(IMarketplaceRating.class);
    final Root<MarketplaceRatingImpl> imr = getByPortlet.from(MarketplaceRatingImpl.class);
    getByPortlet.select(imr);

    //Define the path to the portlet fName
    final Path<MarketplaceRatingPK> mrPK = imr.get("marketplaceRatingPK");
    final Path<PortletDefinitionImpl> mrIPD = mrPK.get("portletDefinition");

    final ParameterExpression<String> portletFName = cb.parameter(String.class, "portletFName");

    getByPortlet.where(cb.equal(mrIPD.get("fname"), portletFName));
    TypedQuery<IMarketplaceRating> tq = entityManager.createQuery(getByPortlet);
    tq.setParameter("portletFName", fname);
    List<IMarketplaceRating> resultList = tq.getResultList();
    Set<IMarketplaceRating> resultSet = new HashSet<IMarketplaceRating>(resultList);
    return resultSet;

}

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

public Path path(String propertyName) {
    if (propertyName.contains(".")) {
        // The propertyName is a path.  Example: createdBy.username, where 'createdBy' is an @Embedded User.
        // Needs to become from.get("createdBy").get("username").
        String[] split = propertyName.split("\\.");
        Path path = from.get(split[0]);
        if (split.length > 1) {
            for (int i = 1; i < split.length; i++) {
                path = path.get(split[i]);
            }// w  ww  . ja  va  2 s.com
        }
        return path;
    } else {
        return from.get(propertyName);
    }
}

From source file:org.broadleafcommerce.core.catalog.dao.IndexFieldCustomPersistenceHandler.java

@Override
public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto,
        DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException {

    FilterAndSortCriteria fieldFsc = cto.getCriteriaMap().get("field");
    if (fieldFsc != null) {
        List<String> filterValues = fieldFsc.getFilterValues();
        boolean didFilter = false;
        cto.getCriteriaMap().remove("field");

        CriteriaBuilder builder = dynamicEntityDao.getStandardEntityManager().getCriteriaBuilder();
        CriteriaQuery<IndexField> criteria = builder.createQuery(IndexField.class);
        Root<IndexFieldImpl> root = criteria.from(IndexFieldImpl.class);
        criteria.select(root);/*from w  w w. j a  va  2s .  co m*/

        // Check if we are searching for specific field names
        List<Predicate> restrictions = new ArrayList<Predicate>();
        if (CollectionUtils.isNotEmpty(filterValues)) {
            restrictions.add(builder.like(root.get("field").<String>get("friendlyName"),
                    "%" + filterValues.get(0) + "%"));
            didFilter = true;
        }

        // Check if this filter value has a sort direction associated with it
        Order order = null;
        for (FilterAndSortCriteria sortCriteria : cto.getCriteriaMap().values()) {
            if (sortCriteria.getSortDirection() != null) {
                Path path = root;
                try {
                    // Try to find the path to the property in IndexFieldImpl
                    String[] pathParts = sortCriteria.getPropertyId().split("\\.");
                    for (String part : pathParts) {
                        path = path.get(part);
                    }

                    // If we made it here, we have the path, set the sorting (asc/desc)
                    if (sortCriteria.getSortAscending()) {
                        order = builder.asc(path);
                    } else {
                        order = builder.desc(path);
                    }
                    criteria.orderBy(order);
                    break;
                } catch (IllegalArgumentException e) {
                    // This isn't an actual entity property
                    continue;
                }
            }
        }

        criteria.where(restrictions.toArray(new Predicate[restrictions.size()]));

        TypedQuery<IndexField> query = dynamicEntityDao.getStandardEntityManager().createQuery(criteria);
        List<IndexField> indexFields = query.getResultList();

        // Convert the result list into a list of entities
        PersistencePerspective persistencePerspective = persistencePackage.getPersistencePerspective();
        Map<String, FieldMetadata> indexFieldMetadata = helper
                .getSimpleMergedProperties(IndexField.class.getName(), persistencePerspective);
        Entity[] entities = helper.getRecords(indexFieldMetadata, indexFields);

        // We need to get the total number of records available because the entityList returned may not be the full set.
        Map<String, FieldMetadata> originalProps = helper.getSimpleMergedProperties(IndexField.class.getName(),
                persistencePerspective);
        List<FilterMapping> filterMappings = helper.getFilterMappings(persistencePerspective, cto,
                IndexField.class.getName(), originalProps);
        int totalRecords = helper.getTotalRecords(persistencePackage.getCeilingEntityFullyQualifiedClassname(),
                filterMappings);

        // Create a Dynamic Result Set from the entity list created above.
        DynamicResultSet resultSet = new DynamicResultSet(entities,
                (didFilter ? entities.length : totalRecords));
        return resultSet;
    }

    DynamicResultSet resultSet = helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto);
    return resultSet;
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachActiveRestriction(Date currentDate, Path<? extends Product> product,
        Path<? extends Sku> sku, List<Predicate> restrictions) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    // Add the product archived status flag restriction
    restrictions.add(builder.or(builder.isNull(product.get("archiveStatus").get("archived")),
            builder.equal(product.get("archiveStatus").get("archived"), 'N')));

    // Add the active start/end date restrictions
    restrictions.add(builder.lessThan(sku.get("activeStartDate").as(Date.class), currentDate));
    restrictions.add(builder.or(builder.isNull(sku.get("activeEndDate")),
            builder.greaterThan(sku.get("activeEndDate").as(Date.class), currentDate)));
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachOrderBy(SearchCriteria searchCriteria, From<?, ? extends Product> product,
        Path<? extends Sku> sku, CriteriaQuery<?> criteria) {
    if (StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        List<Order> sorts = new ArrayList<Order>();

        String sortQueries = searchCriteria.getSortQuery();
        for (String sortQuery : sortQueries.split(",")) {
            String[] sort = sortQuery.split(" ");
            if (sort.length == 2) {
                String key = sort[0];
                boolean asc = sort[1].toLowerCase().contains("asc");

                // Determine whether we should use the product path or the sku path
                Path<?> pathToUse;
                if (key.contains("defaultSku.")) {
                    pathToUse = sku;/*  w  w w  . j  a v a2 s  .  c om*/
                    key = key.substring("defaultSku.".length());
                } else if (key.contains("product.")) {
                    pathToUse = product;
                    key = key.substring("product.".length());
                } else {
                    // We don't know which path this facet is built on - resolves previous bug that attempted
                    // to attach search facet to any query parameter
                    continue;
                }

                if (asc) {
                    sorts.add(builder.asc(pathToUse.get(key)));
                } else {
                    sorts.add(builder.desc(pathToUse.get(key)));
                }
            }
        }

        criteria.orderBy(sorts.toArray(new Order[sorts.size()]));
    }
}

From source file:org.broadleafcommerce.core.catalog.dao.ProductDaoImpl.java

protected void attachSearchCriteria(SearchCriteria searchCriteria, From<?, ? extends Product> product,
        From<?, ? extends Sku> sku, List<Predicate> restrictions) {
    CriteriaBuilder builder = em.getCriteriaBuilder();

    // Build out the filter criteria from the users request
    for (Entry<String, String[]> entry : searchCriteria.getFilterCriteria().entrySet()) {
        String key = entry.getKey();
        List<String> eqValues = new ArrayList<String>();
        List<String[]> rangeValues = new ArrayList<String[]>();

        // Determine which path is the appropriate one to use
        Path<?> pathToUse;
        if (key.contains("defaultSku.")) {
            pathToUse = sku;/*from w ww.  jav a2s .  co m*/
            key = key.substring("defaultSku.".length());
        } else if (key.contains("productAttributes.")) {
            pathToUse = product.join("productAttributes");

            key = key.substring("productAttributes.".length());
            restrictions.add(builder.equal(pathToUse.get("name").as(String.class), key));

            key = "value";
        } else if (key.contains("product.")) {
            pathToUse = product;
            key = key.substring("product.".length());
        } else {
            // We don't know which path this facet is built on - resolves previous bug that attempted
            // to attach search facet to any query parameter
            continue;
        }

        // Values can be equality checks (ie manufacturer=Dave's) or range checks, which take the form
        // key=range[minRange:maxRange]. Figure out what type of check this is
        for (String value : entry.getValue()) {
            if (value.contains("range[")) {
                String[] rangeValue = new String[] {
                        value.substring(value.indexOf("[") + 1, value.indexOf(":")),
                        value.substring(value.indexOf(":") + 1, value.indexOf("]")) };
                rangeValues.add(rangeValue);
            } else {
                eqValues.add(value);
            }
        }

        // Add the equality range restriction with the "in" builder. That means that the query string
        // ?manufacturer=Dave&manufacturer=Bob would match either Dave or Bob
        if (eqValues.size() > 0) {
            restrictions.add(pathToUse.get(key).in(eqValues));
        }

        // If we have any range restrictions, we need to build those too. Ranges are also "or"ed together,
        // such that specifying range[0:5] and range[10:null] for the same field would match items
        // that were valued between 0 and 5 OR over 10 for that field
        List<Predicate> rangeRestrictions = new ArrayList<Predicate>();
        for (String[] range : rangeValues) {
            BigDecimal min = new BigDecimal(range[0]);
            BigDecimal max = null;
            if (range[1] != null && !range[1].equals("null")) {
                max = new BigDecimal(range[1]);
            }

            Predicate minRange = builder.greaterThan(pathToUse.get(key).as(BigDecimal.class), min);
            Predicate maxRange = null;
            if (max != null) {
                maxRange = builder.lessThan(pathToUse.get(key).as(BigDecimal.class), max);
                rangeRestrictions.add(builder.and(minRange, maxRange));
            } else {
                rangeRestrictions.add(minRange);
            }
        }

        if (rangeRestrictions.size() > 0) {
            restrictions.add(builder.or(rangeRestrictions.toArray(new Predicate[rangeRestrictions.size()])));
        }
    }
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.module.criteria.FieldPathBuilder.java

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public Path getPath(From root, FieldPath fieldPath, final CriteriaBuilder builder) {
    FieldPath myFieldPath = fieldPath;/*from  ww w .  j  av  a2 s  . c om*/
    if (!StringUtils.isEmpty(fieldPath.getTargetProperty())) {
        myFieldPath = getFieldPath(root, fieldPath.getTargetProperty());
    }
    From myRoot = root;
    for (String pathElement : myFieldPath.getAssociationPath()) {
        myRoot = myRoot.join(pathElement);
    }
    Path path = myRoot;

    for (int i = 0; i < myFieldPath.getTargetPropertyPieces().size(); i++) {
        String piece = myFieldPath.getTargetPropertyPieces().get(i);

        if (path.getJavaType().isAnnotationPresent(Embeddable.class)) {
            String original = ((SingularAttributePath) path).getAttribute().getDeclaringType().getJavaType()
                    .getName() + "." + ((SingularAttributePath) path).getAttribute().getName() + "." + piece;
            String copy = path.getJavaType().getName() + "." + piece;
            copyCollectionPersister(original, copy,
                    ((CriteriaBuilderImpl) builder).getEntityManagerFactory().getSessionFactory());
        }

        try {
            path = path.get(piece);
        } catch (IllegalArgumentException e) {
            // We weren't able to resolve the requested piece, likely because it's in a polymoprhic version
            // of the path we're currently on. Let's see if there's any polymoprhic version of our class to
            // use instead.
            EntityManagerFactoryImpl em = ((CriteriaBuilderImpl) builder).getEntityManagerFactory();
            Metamodel mm = em.getMetamodel();
            boolean found = false;

            Class<?>[] polyClasses = dynamicDaoHelper.getAllPolymorphicEntitiesFromCeiling(path.getJavaType(),
                    em.getSessionFactory(), true, true);

            for (Class<?> clazz : polyClasses) {
                ManagedType mt = mm.managedType(clazz);
                try {
                    Attribute attr = mt.getAttribute(piece);
                    if (attr != null) {
                        Root additionalRoot = criteria.from(clazz);
                        restrictions.add(builder.equal(path, additionalRoot));
                        path = additionalRoot.get(piece);
                        found = true;
                        break;
                    }
                } catch (IllegalArgumentException e2) {
                    // Do nothing - we'll try the next class and see if it has the attribute
                }
            }

            if (!found) {
                throw new IllegalArgumentException(
                        "Could not resolve requested attribute against path, including"
                                + " known polymorphic versions of the root",
                        e);
            }
        }

        if (path.getParentPath() != null
                && path.getParentPath().getJavaType().isAnnotationPresent(Embeddable.class)
                && path instanceof PluralAttributePath) {
            //We need a workaround for this problem until it is resolved in Hibernate (loosely related to and likely resolved by https://hibernate.atlassian.net/browse/HHH-8802)
            //We'll throw a specialized exception (and handle in an alternate flow for calls from BasicPersistenceModule)
            throw new CriteriaConversionException(String.format(
                    "Unable to create a JPA criteria Path through an @Embeddable object to a collection that resides therein (%s)",
                    fieldPath.getTargetProperty()), fieldPath);
            //                //TODO this code should work, but there still appear to be bugs in Hibernate's JPA criteria handling for lists
            //                //inside Embeddables
            //                Class<?> myClass = ((PluralAttributePath) path).getAttribute().getClass().getInterfaces()[0];
            //                //we don't know which version of "join" to call, so we'll let reflection figure it out
            //                try {
            //                    From embeddedJoin = myRoot.join(((SingularAttributePath) path.getParentPath()).getAttribute());
            //                    Method join = embeddedJoin.getClass().getMethod("join", myClass);
            //                    path = (Path) join.invoke(embeddedJoin, ((PluralAttributePath) path).getAttribute());
            //                } catch (Exception e) {
            //                    throw new RuntimeException(e);
            //                }
        }
    }

    return path;
}