Java Code Examples for javax.persistence.criteria.Path#get()

The following examples show how to use javax.persistence.criteria.Path#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PathSpecification.java    From specification-arg-resolver with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <F> Path<F> path(Root<T> root) {
    Path<?> expr = null;
    for (String field : path.split("\\.")) {
        if (expr == null) {
        	if (queryContext != null && queryContext.getEvaluated(field, root) != null) {
        		expr = (Path<T>) queryContext.getEvaluated(field, root);
        	} else {
        		expr = root.get(field);
        	}
        } else {
            expr = expr.get(field);
        }
    }
    return (Path<F>) expr;
}
 
Example 2
Source File: ServiceFacade.java    From aws-photosharing-example with Apache License 2.0 6 votes vote down vote up
private <T> List<Order> getSort(Root<T> p_root, CriteriaBuilder p_builder, Sort[] p_sort) {
	
	List<Order> order = new LinkedList<Order>();
	
	if (p_sort != null && p_sort.length > 0) {				
		
		for (Sort sort : p_sort) {
			Path<?> property_path = null;		
			
			for (String hop : sort.getPropertyPath()) {
				if (property_path == null)
					property_path = p_root.get(hop);
				else
					property_path = property_path.get(hop);
			}
			if (sort.getOrderAscending()) {
				order.add(p_builder.asc(property_path));
			} else {
				order.add(p_builder.desc(property_path));
			}
		}			
	}
	
	return order;
}
 
Example 3
Source File: RSQLUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static Optional<Path<?>> getFieldPath(final Root<?> root, final String[] split, final boolean isMapKeyField,
                                              final BiFunction<Path<?>, String, Path<?>> joinFieldPathProvider) {
    Path<?> fieldPath = null;
    for (int i = 0; i < split.length; i++) {
        if (!(isMapKeyField && i == (split.length - 1))) {
            final String fieldNameSplit = split[i];
            fieldPath = (fieldPath != null) ? fieldPath.get(fieldNameSplit) : root.get(fieldNameSplit);
            fieldPath = joinFieldPathProvider.apply(fieldPath, fieldNameSplit);
        }
    }
    return Optional.ofNullable(fieldPath);
}
 
Example 4
Source File: JpaUtil.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert the passed propertyPath into a JPA path.
 * <p>
 * Note: JPA will do joins if the property is in an associated entity.
 */
@SuppressWarnings("unchecked")
public static <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        // handle case when order on already fetched attribute
        for (Fetch<E, ?> fetch : root.getFetches()) {
            if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                path = (Join<E, ?>) fetch;
                found = true;
                break;
            }
        }
        for (Join<E, ?> join : root.getJoins()) {
            if (attribute.getName().equals(join.getAttribute().getName())) {
                path = join;
                found = true;
                break;
            }
        }
        if (!found) {
            path = path.get(attribute.getName());
        }
    }
    return (Path<F>) path;
}
 
Example 5
Source File: JpaUtil.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert the passed propertyPath into a JPA path. Note: JPA will do joins
 * if the property is in an associated
 * entity.
 */
private static <E> Path<?> getPropertyPath(final Path<E> root, final String propertyPath) {
    String[] pathItems = StringUtils.split(propertyPath, ".");

    Path<?> path = root.get(pathItems[0]);
    for (int i = 1; i < pathItems.length; i++) {
        path = path.get(pathItems[i]);
    }
    return path;
}
 
Example 6
Source File: AbstractJPATypedQueryVisitor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Path<?> getNextPath(Path<?> element, String name, String postName,
    ClassValue cv, CollectionCheckInfo collSize) {
    final boolean isCollectionOrJoin = collSize == null
        && (cv.isCollection(name) || isJoinProperty(name) || existingCollectionInPostName(cv, postName))
        && (element == root || element instanceof Join);
    if (isCollectionOrJoin) {
        final Path<?> path = getExistingJoinProperty((From<?, ?>)element, name);
        if (path != null) {
            return path;
        }
        return element == root ? root.join(name) : ((Join<?, ?>)element).join(name);
    }
    return element.get(name);
}
 
Example 7
Source File: In.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public List<Predicate> build(CriteriaBuilder builder, Path<P> path)
{
    Path<V> p = path.get(singular);
    CriteriaBuilder.In<V> in = builder.in(p);
    for (V value : values)
    {
        if (value != null)
        {
            in.value(value);
        }
    }
    return Arrays.asList((Predicate) in);
}
 
Example 8
Source File: RSQLUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private Path<Object> getMapValueFieldPath(final A enumField, final Path<Object> fieldPath) {
    final String valueFieldNameFromSubEntity = enumField.getSubEntityMapTuple().map(Entry::getValue)
            .orElse(null);

    if (!enumField.isMap() || valueFieldNameFromSubEntity == null) {
        return fieldPath;
    }
    return fieldPath.get(valueFieldNameFromSubEntity);
}
 
Example 9
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private static void processEqualsOperator(CriteriaBuilder cb, List<Predicate> predicates, String filed, Object value, Path path) {
    Expression filterExpr = path.get(filed);
    if (value instanceof String) {
        predicates.add(cb.equal(cb.upper(filterExpr), (String) value.toString().toUpperCase()));
    } else {
        predicates.add(cb.equal(filterExpr, value));
    }

}
 
Example 10
Source File: RdbmsUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * @param expression : entity has multi level field this field name from parent root path
 * @param builder : Hibernate criteria builder
 * @param fieldType : For example, artifact has the single table but type is different like
 *     dataset(artifact), artifact(artifact) etc.
 * @param key : artifact.key
 * @param predicate : field contain the keyValue and operator for query which is set by frontend
 * @return {@link List<Predicate>} : which contain the where clause condition(predicate) created
 *     from KeyValueQuery base on artifact
 * @throws InvalidProtocolBufferException InvalidProtocolBufferException
 */
private static List<Predicate> getArtifactTypePredicates(
    Path expression,
    CriteriaBuilder builder,
    String fieldType,
    String key,
    KeyValueQuery predicate)
    throws InvalidProtocolBufferException {
  List<Predicate> fieldPredicates = new ArrayList<>();
  Predicate fieldTypePredicate =
      builder.equal(expression.get(ModelDBConstants.FEILD_TYPE), fieldType);
  fieldPredicates.add(fieldTypePredicate);

  Path valueExpression;
  if (key.equals(ModelDBConstants.LINKED_ARTIFACT_ID)) {
    valueExpression = expression.get(key);
  } else {
    Predicate keyPredicate = builder.equal(expression.get(ModelDBConstants.KEY), key);
    fieldPredicates.add(keyPredicate);
    valueExpression = expression.get(ModelDBConstants.PATH);
  }

  if (predicate != null) {
    Predicate valuePredicate =
        getValuePredicate(builder, ModelDBConstants.ARTIFACTS, valueExpression, predicate, true);
    fieldPredicates.add(valuePredicate);
  }

  return fieldPredicates;
}
 
Example 11
Source File: JpaUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a Path from Path using property path
 * @param path the base path
 * @param propertyPath property path String like "customer.order.price"
 * @return a new Path for property
 */
@SuppressWarnings("unchecked")
public static <T> Path<T> getPath(Path<?> path, String propertyPath) {
	if (StringUtils.isEmpty(propertyPath))
		return (Path<T>) path;
	
	String name = StringUtils.substringBefore(propertyPath, PropertyUtils.PROPERTY_SEPARATOR);
	Path<?> p = path.get(name); 
	
	return getPath(p, StringUtils.substringAfter(propertyPath, PropertyUtils.PROPERTY_SEPARATOR));
	
}
 
Example 12
Source File: ServiceFacade.java    From aws-photosharing-example with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Predicate getFilterPredicate(Function<Predicate[], Predicate>  p_method, Root<T> p_root, CriteriaBuilder p_builder, Filter[] p_filter) {
	 
	 Predicate predicate = null;
	 
	 if (p_filter != null && p_filter.length > 0) {	
			Path<?> property_path = null;							
			LinkedList<Predicate> predicates = new LinkedList<Predicate>();				
			
			for (Filter filter: p_filter) {							
				for (String hop : filter.getPropertyPath()) {
					if (property_path == null)
						property_path = p_root.get(hop);
					else
						property_path = property_path.get(hop);
				}
				if (filter.getValue() != null) {
					if (filter.isExact())
						predicates.add(p_builder.equal(property_path, filter.getValue()));
					else
						predicates.add(p_builder.like((Expression<String>) property_path, filter.getValue()+"%"));
				} else {
					if (filter.isInverse())
						predicates.add(p_builder.isNotNull(property_path));
					else
						predicates.add(p_builder.isNull(property_path));
				}
				
				property_path = null;					
			}											
			
			if (predicates.size() > 1)
				predicate = p_method.apply(predicates.toArray(new Predicate[predicates.size()]));
			else
				predicate = predicates.get(0);							
	}				 
	return predicate;
 }
 
Example 13
Source File: ServiceFacade.java    From aws-photosharing-example with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private <C,T> Predicate getIsMemberOfPredicate(Root<C> p_root, CriteriaBuilder p_builder, Filter p_filter) {
	if (p_filter == null)
		return null;
	
	Path<? extends Collection> property_path = null;	
	
	for (String hop : p_filter.getPropertyPath()) {
		if (property_path == null)
			property_path = p_root.get(hop);
		else
			property_path = property_path.get(hop);
	}		
	return p_builder.isMember(p_filter.getValue(), property_path);
}
 
Example 14
Source File: EntityQuery.java    From onedev with MIT License 5 votes vote down vote up
public static <T> Path<T> getPath(Path<?> root, String pathName) {
	int index = pathName.indexOf('.');
	if (index != -1) {
		Path<T> path = root.get(pathName.substring(0, index));
		for (String field: Splitter.on(".").split(pathName.substring(index+1))) 
			path = path.get(field);
		return path;
	} else {
		return root.get(pathName);
	}
}
 
Example 15
Source File: DynamicSpecifications.java    From wenku with MIT License 4 votes vote down vote up
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) {
    return new Specification<T>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (Collections3.isNotEmpty(filters)) {

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

                    // logic operator
                    switch (filter.operator) {
                        case EQ :
                            predicates.add(builder.equal(expression, filter.value));
                            break;
                        case LIKE :
                            predicates.add(builder.like(expression, "%" + filter.value + "%"));
                            break;
                        case GT :
                            predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
                            break;
                        case LT :
                            predicates.add(builder.lessThan(expression, (Comparable) filter.value));
                            break;
                        case GTE :
                            predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
                            break;
                        case LTE :
                            predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
                            break;
                        case IN :
                            predicates.add(expression.in(Arrays.asList(filter.value.toString().split(","))));
                            break;
                    }
                }

                // 将所有条件用 and 联合起来
                if (!predicates.isEmpty()) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
            }

            return builder.conjunction();
        }
    };
}
 
Example 16
Source File: AttributeQuerySelection.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Override
public <R> Selection<X> toSelection(CriteriaQuery<R> query, CriteriaBuilder builder, Path<? extends P> path)
{
    return path.get(getAttribute());
}
 
Example 17
Source File: SimpleExpression.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    Path expression = null;
    if (fieldName.contains(".")) {
        
        System.out.println(root);
        String[] names = StringUtils.split(fieldName, ".");
        expression = root.get(names[0]);
        for (int i = 1; i < names.length; i++) {
            expression = expression.get(names[i]);
        }
    } else {
        expression = root.get(fieldName);
    }

    switch (operator) {
    case EQ:
        return builder.equal(expression, value);
    case NE:
        return builder.notEqual(expression, value);
    case LIKE:
        return builder.like((Expression<String>) expression, "%" + value + "%");
    case RLIKE:
        return builder.like((Expression<String>) expression, value + "%");
    case LLIKE:
        return builder.like((Expression<String>) expression, value + "%");
    case LT:
        return builder.lessThan(expression, (Comparable) value);
    case GT:
        return builder.greaterThan(expression, (Comparable) value);
    case LTE:
        return builder.lessThanOrEqualTo(expression, (Comparable) value);
    case GTE:
        return builder.greaterThanOrEqualTo(expression, (Comparable) value);
    case ISNULL:
        return builder.isNull(expression);
    case NOTNULL:
        return builder.isNotNull(expression);
    case IN:
        return builder.in(expression);
    default:
        return null;
    }
}
 
Example 18
Source File: SimpleExpression.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
    Path expression = null;
    if (fieldName.contains(".")) {
        
        System.out.println(root);
        String[] names = StringUtils.split(fieldName, ".");
        expression = root.get(names[0]);
        for (int i = 1; i < names.length; i++) {
            expression = expression.get(names[i]);
        }
    } else {
        expression = root.get(fieldName);
    }

    switch (operator) {
    case EQ:
        return builder.equal(expression, value);
    case NE:
        return builder.notEqual(expression, value);
    case LIKE:
        return builder.like((Expression<String>) expression, "%" + value + "%");
    case RLIKE:
        return builder.like((Expression<String>) expression, value + "%");
    case LLIKE:
        return builder.like((Expression<String>) expression, value + "%");
    case LT:
        return builder.lessThan(expression, (Comparable) value);
    case GT:
        return builder.greaterThan(expression, (Comparable) value);
    case LTE:
        return builder.lessThanOrEqualTo(expression, (Comparable) value);
    case GTE:
        return builder.greaterThanOrEqualTo(expression, (Comparable) value);
    case ISNULL:
        return builder.isNull(expression);
    case NOTNULL:
        return builder.isNotNull(expression);
    default:
        return null;
    }
}
 
Example 19
Source File: DynamicSpecifications.java    From dubai with MIT License 4 votes vote down vote up
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) {
	return new Specification<T>() {
		@Override
		public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
			if (Collections3.isNotEmpty(filters)) {

				List<Predicate> predicates = Lists.newArrayList();
				for (SearchFilter filter : filters) {
					// nested path translate, 如Task的名为"user.name"的filedName, 转换为Task.user.name属性
					String[] names = StringUtils.split(filter.fieldName, ".");
					Path expression = root.get(names[0]);
					for (int i = 1; i < names.length; i++) {
						expression = expression.get(names[i]);
					}

					// logic operator
					switch (filter.operator) {
					case EQ:
						predicates.add(builder.equal(expression, filter.value));
						break;
					case LIKE:
						predicates.add(builder.like(expression, "%" + filter.value + "%"));
						break;
					case GT:
						predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
						break;
					case LT:
						predicates.add(builder.lessThan(expression, (Comparable) filter.value));
						break;
					case GTE:
						predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value));
						break;
					case LTE:
						predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value));
						break;
					}
				}

				// 将所有条件用 and 联合起来
				if (!predicates.isEmpty()) {
					return builder.and(predicates.toArray(new Predicate[predicates.size()]));
				}
			}

			return builder.conjunction();
		}
	};
}
 
Example 20
Source File: QueryHelper.java    From cia with Apache License 2.0 3 votes vote down vote up
/**
 * Equals ignore case if string predicate.
 *
 * @param <T>
 *            the generic type
 * @param criteriaBuilder
 *            the criteria builder
 * @param path
 *            the path
 * @param value
 *            the value
 * @param property
 *            the property
 * @return the predicate
 */
public static <T> Predicate equalsIgnoreCaseIfStringPredicate(final CriteriaBuilder criteriaBuilder,final Path<T> path,
		final Object value, final SingularAttribute<T, ? extends Object> property) {
	Predicate condition;
	if (value instanceof String) {
		final Expression<String> propertyObject = (Expression<String>) path.get(property);
		condition = criteriaBuilder.equal(criteriaBuilder.upper(propertyObject), ((String) value).toUpperCase(Locale.ENGLISH));

	} else {
		condition = criteriaBuilder.equal(path.get(property), value);
	}
	return condition;
}