Package javax.persistence.criteria

Examples of javax.persistence.criteria.Path


  }

  @Override
  @SuppressWarnings("unchecked")
  public CriteriaUpdate<T> set(String attributeName, Object value) {
    final Path attributePath = getRoot().get( attributeName );
    final Expression valueExpression = value == null
        ? criteriaBuilder().nullLiteral( attributePath.getJavaType() )
        : criteriaBuilder().literal( value );
    addAssignment( attributePath, valueExpression );
    return this;
  }
View Full Code Here


    CriteriaQuery cq = cb.createQuery();
    Root<Book> candidate = cq.from(Book.class);
    candidate.alias("b");
    cq.select(candidate);

    Path titleField = candidate.get("title");
    cq.where(cb.equal(titleField, "Bar Book"));

    Path isbnField = candidate.get("isbn");
    cq.orderBy(cb.desc(isbnField));

    Query q = em.createQuery(cq);
    List<Book> books = q.getResultList();
    assertNotNull(books);
View Full Code Here

    }
   
    protected void addRestrictions(String ceilingEntity, List<FilterMapping> filterMappings, CriteriaBuilder criteriaBuilder,
                                   Root original, List<Predicate> restrictions, List<Order> sorts, CriteriaQuery criteria) {
        for (FilterMapping filterMapping : filterMappings) {
            Path explicitPath = null;
            if (filterMapping.getFieldPath() != null) {
                explicitPath = filterMapping.getRestriction().getFieldPathBuilder().getPath(original, filterMapping.getFieldPath(), criteriaBuilder);
            }

            if (filterMapping.getRestriction() != null) {
                List directValues = null;
                boolean shouldConvert = true;
                if (CollectionUtils.isNotEmpty(filterMapping.getFilterValues())) {
                    directValues = filterMapping.getFilterValues();
                } else if (CollectionUtils.isNotEmpty(filterMapping.getDirectFilterValues()) || (filterMapping.getDirectFilterValues() != null && filterMapping.getDirectFilterValues() instanceof EmptyFilterValues)) {
                    directValues = filterMapping.getDirectFilterValues();
                    shouldConvert = false;
                }
               
                if (directValues != null) {
                    Predicate predicate = filterMapping.getRestriction().buildRestriction(criteriaBuilder, original,
                            ceilingEntity, filterMapping.getFullPropertyName(), explicitPath, directValues, shouldConvert,
                            criteria, restrictions);
                    restrictions.add(predicate);
                }
            }

            if (filterMapping.getSortDirection() != null) {
                Path sortPath = explicitPath;
                if (sortPath == null && !StringUtils.isEmpty(filterMapping.getFullPropertyName())) {
                    FieldPathBuilder fieldPathBuilder = filterMapping.getRestriction().getFieldPathBuilder();
                    fieldPathBuilder.setCriteria(criteria);
                    fieldPathBuilder.setRestrictions(restrictions);
                    sortPath = filterMapping.getRestriction().getFieldPathBuilder().getPath(original, filterMapping.getFullPropertyName(), criteriaBuilder);
View Full Code Here

        List<String> basicProperties = new ArrayList<String>();
        int j = 0;
        for (String piece : pieces) {
            checkPiece: {
                if (j == 0) {
                    Path path = root.get(piece);
                    if (path instanceof PluralAttributePath) {
                        associationPath.add(piece);
                        break checkPiece;
                    }
                }
View Full Code Here

        }
        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
View Full Code Here

                                                From root, String ceilingEntity, String fullPropertyName,
                                                Path explicitPath, List directValues) {
                    FieldPath fieldPath = fieldPathBuilder.getFieldPath(root, fullPropertyName);
                    if ((StringUtils.isNotEmpty(skuPropertyPrefix) && fullPropertyName.startsWith(skuPropertyPrefix))
                                            || CollectionUtils.isEmpty(fieldPath.getAssociationPath())) {
                        Path targetPropertyPath = fieldPathBuilder.getPath(root, fieldPath, builder);
                        Path defaultSkuPropertyPath = fieldPathBuilder.getPath(root,
                                DEFAULT_SKU_PATH_PREFIX + fullPropertyName, builder);
                        Path productPath = fieldPathBuilder.getPath(root, "product", builder);
                        Predicate propertyExpression;
                        Predicate defaultSkuExpression;
                        if (delegateRestriction.getPredicateProvider() instanceof LikePredicateProvider) {
                                propertyExpression = builder.like(builder.lower(targetPropertyPath),
                                        ((String) directValues.get(0)).toLowerCase());
View Full Code Here

                     */
                    if (fields.length == 2) {
                        /*
                         * Get main attribute
                         */
                        Path attr = from.get(fields[0]);
                        /*
                         * If filterable column is id then just get desired object by it's identifier
                         */
                        if (fields[1].equals(NamingConstants.ID)) {
                            try {
                                BigInteger id = BigInteger.valueOf(NumberFormat.getInstance().parse(var.toString()).longValue());
                                Object value = getEntityManager().find(attr.getJavaType(), id);
                                preList.add(builder.equal(from.get(fields[0]), value));
                            }
                            catch (ParseException ex) {
                                Logger.getLogger(AbstractFacade.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                        else {
                            /*
                             * Create subquery to find by attribute
                             */
                            Subquery subquery = cq.subquery(attr.getJavaType());
                            Root fromAttr = subquery.from(attr.getJavaType());
                            subquery.select(fromAttr.get(NamingConstants.ID));

                            if (var instanceof String && ((String)var).contains("%")) {
                                /*
                                 * This is a like query
                                 */
                                subquery.where(builder.like(builder.lower(fromAttr.get(fields[1])), var.toString().toLowerCase()));  
                            }
                            else {
                                /*
                                 * This is strong equals query
                                 */
                                subquery.where(builder.equal(fromAttr.get(fields[1]), var));
                            }

                            /*
                             * Add where to main query
                             */
                            preList.add(builder.in(from.get(fields[0]).get(NamingConstants.ID)).value(subquery));
                        }
                    }
                    else
                        /*
                         * Just skip this filter becauseit's unusable
                         */
                        continue;
                }
                else {
                    Path ptAttr = from.get(column);
                    Class<?> cl = ptAttr.getJavaType();
                    if (cl.equals(String.class)) {
                        if (var instanceof String && ((String)var).contains("%")) {
                            Expression<String> literal = from.get(column);
                            preList.add(builder.like(builder.lower(literal), var.toString().toLowerCase()));
                        }
View Full Code Here

     * @return Path to desired property
     */
    public static Path getCriteriaPath(Root root, String path) {
        String[] splittedPath = path.split("\\.");

        Path result = root.get(splittedPath[0]);

        for (int i = 1; i < splittedPath.length; i++) {
            result = result.get(splittedPath[i]);
        }

        return result;
    }
View Full Code Here

        if (filterSet != null && !filterSet.isEmpty()) {
          List<Predicate> predicates = new ArrayList<Predicate>();
          for (SearchFilter filter : filterSet) {
            // nested path translate, 如Task的名为"user.name"的filedName, 转换为Task.user.name属性
            String[] names = StringUtils.split(filter.getFieldName(), ".");
            Path expression = root.get(names[0]);
            for (int i = 1; i < names.length; i++) {
              expression = expression.get(names[i]);
            }

            // 自动进行enum和date的转换。
            Class clazz = expression.getJavaType();
            if (Date.class.isAssignableFrom(clazz) && !filter.getValue().getClass().equals(clazz)) {
              filter.setValue(convert2Date((String)filter.getValue()));
            } else if (Enum.class.isAssignableFrom(clazz) && !filter.getValue().getClass().equals(clazz)) {
              filter.setValue(convert2Enum(clazz, (String)filter.getValue()));
            }
           
            // logic operator
            switch (filter.getOperator()) {
            case EQ:
              predicates.add(builder.equal(expression, filter.getValue()));
              break;
            case LIKE:
              predicates.add(builder.like(expression, "%" + filter.getValue() + "%"));
              break;
            case GT:
              predicates.add(builder.greaterThan(expression, (Comparable) filter.getValue()));
              break;
            case LT:
              predicates.add(builder.lessThan(expression, (Comparable) filter.getValue()));
              break;
            case GTE:
              predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.getValue()));
              break;
            case LTE:
              predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.getValue()));
              break;
            case IN:
              predicates.add(builder.and(expression.in((Object[])filter.getValue())));
              break;
            }
          }

          // 将所有条件用 and 联合起来
View Full Code Here

  }

  @Override
  @SuppressWarnings("unchecked")
  public CriteriaUpdate<T> set(String attributeName, Object value) {
    final Path attributePath = getRoot().get( attributeName );
    final Expression valueExpression = value == null
        ? criteriaBuilder().nullLiteral( attributePath.getJavaType() )
        : criteriaBuilder().literal( value );
    addAssignment( attributePath, valueExpression );
    return this;
  }
View Full Code Here

TOP

Related Classes of javax.persistence.criteria.Path

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.