com.querydsl.core.types.Path Java Examples

The following examples show how to use com.querydsl.core.types.Path. 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: KeyValueQuerydslUtils.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Expression} for the given {@link Order} property.
 *
 * @param order must not be {@literal null}.
 * @param builder must not be {@literal null}.
 * @return
 */
private static Expression<?> buildOrderPropertyPathFrom(Order order, PathBuilder<?> builder) {

	Assert.notNull(order, "Order must not be null!");
	Assert.notNull(builder, "Builder must not be null!");

	PropertyPath path = PropertyPath.from(order.getProperty(), builder.getType());
	Expression<?> sortPropertyExpression = builder;

	while (path != null) {

		if (!path.hasNext() && order.isIgnoreCase()) {
			// if order is ignore-case we have to treat the last path segment as a String.
			sortPropertyExpression = Expressions.stringPath((Path<?>) sortPropertyExpression, path.getSegment()).lower();
		} else {
			sortPropertyExpression = Expressions.path(path.getType(), (Path<?>) sortPropertyExpression, path.getSegment());
		}

		path = path.next();
	}

	return sortPropertyExpression;
}
 
Example #2
Source File: QuerydslPredicateOperationCustomizer.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/***
 * Tries to figure out the Type of the field. It first checks the Qdsl pathSpecMap before checking the root class. Defaults to String.class
 * @param fieldName The name of the field used as reference to get the type
 * @param pathSpecMap The Qdsl path specifications as defined in the resolved bindings
 * @param root The root type where the paths are gotten
 * @return The type of the field. Returns
 */
private Type getFieldType(String fieldName, Map<String, Object> pathSpecMap, Class<?> root) {
	try {
		Object pathAndBinding = pathSpecMap.get(fieldName);
		Optional<Path<?>> path = getPathFromPathSpec(pathAndBinding);

		Type genericType;
		Field declaredField = null;
		if (path.isPresent()) {
			genericType = path.get().getType();
		}
		else {
			declaredField = root.getDeclaredField(fieldName);
			genericType = declaredField.getGenericType();
		}
		if (genericType != null) {
			return genericType;
		}
	}
	catch (NoSuchFieldException e) {
		LOGGER.warn("Field {} not found on {} : {}", fieldName, root.getName(), e.getMessage());
	}
	return String.class;
}
 
Example #3
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a global contains text filter on the provided attributes.
 * WARNING: this creates a very inefficient query. If you have many entity
 * instances to query, use instead an indexed text search solution for better
 * performance.
 * @param text the text to look for
 * @param query
 * @param globalSearchAttributes the list of attributes to perform the
 *        filter on
 * @return the updated query
 */
protected JPQLQuery<T> applyGlobalSearch(String text, JPQLQuery<T> query,
    Path<?>... globalSearchAttributes) {
  if (text != null && !StringUtils.isEmpty(text) && globalSearchAttributes.length > 0) {
    BooleanBuilder searchCondition = new BooleanBuilder();
    for (int i = 0; i < globalSearchAttributes.length; i++) {
      Path<?> path = globalSearchAttributes[i];
      if (path instanceof StringPath) {
        StringPath stringPath = (StringPath) path;
        searchCondition.or(stringPath.containsIgnoreCase(text));
      } else if (path instanceof NumberExpression) {
        searchCondition.or(((NumberExpression<?>) path).like("%".concat(text).concat("%")));
      }
    }
    return query.where(searchCondition);
  }
  return query;
}
 
Example #4
Source File: QueryDslRepositorySupportExtTest.java    From springlets with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link io.springlets.data.jpa.repository.support.QueryDslRepositorySupportExt#applyPagination(org.springframework.data.domain.Pageable, com.querydsl.jpa.JPQLQuery, java.util.Map)}.
 */
@Test
public void applyPaginationWithPageableHavingAPropertyNotIncludedInTheAttributeMappingShouldNotFail() {
  // Prepare
  Sort.Order order = new Sort.Order("test");

  Map<String, Path<?>[]> attributeMapping = new HashMap<>();
  when(pageable.getSort()).thenReturn(sort);
  when(pageable.getPageSize()).thenReturn(1);
  when(sort.iterator()).thenReturn(iterator);
  when(iterator.hasNext()).thenReturn(true).thenReturn(false);
  when(iterator.next()).thenReturn(order).thenThrow(new NoSuchElementException());

  // Exercise & verify
  support.applyPagination(pageable, null, attributeMapping);
}
 
Example #5
Source File: RSQLQueryDslSupport.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
public static BooleanExpression toPredicate(final String rsqlQuery, final Path qClazz, final Map<String, String> propertyPathMapper) {
	log.debug("toPredicate({},qClazz:{},propertyPathMapper:{})", rsqlQuery, qClazz);
	if (StringUtils.hasText(rsqlQuery)) {
		return new RSQLParser(RSQLOperators.supportedOperators())
				.parse(rsqlQuery)
				.accept(new RSQLQueryDslPredicateConverter(propertyPathMapper), qClazz);
	} else {
		return null;
	}
}
 
Example #6
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public QuerydslQueryBackend(QuerydslQueryImpl<T> queryImpl, Class<T> clazz, MetaDataObject parentMeta,
		MetaAttribute parentAttr, boolean addParentSelection) {
	this.queryImpl = queryImpl;

	JPAQueryFactory queryFactory = queryImpl.getQueryFactory();

	if (parentMeta != null) {
		parentFrom = QuerydslUtils.getEntityPath(parentMeta.getImplementationClass());
		root = QuerydslUtils.getEntityPath(clazz);

		Path joinPath = (Path) QuerydslUtils.get(parentFrom, parentAttr.getName());
		joinHelper = new JoinRegistry<>(this, queryImpl);

		joinHelper.putJoin(new MetaAttributePath(), root);

		if (addParentSelection) {
			Expression<Object> parentIdExpr = getParentIdExpression(parentMeta, parentAttr);
			querydslQuery = queryFactory.select(parentIdExpr, root);
		}
		else {
			querydslQuery = queryFactory.select(root);
		}

		querydslQuery = querydslQuery.from(parentFrom);
		if (joinPath instanceof CollectionExpression) {
			querydslQuery = querydslQuery.join((CollectionExpression) joinPath, root);
		}
		else {
			querydslQuery = querydslQuery.join((EntityPath) joinPath, root);
		}
	}
	else {
		root = QuerydslUtils.getEntityPath(clazz);
		joinHelper = new JoinRegistry<>(this, queryImpl);
		joinHelper.putJoin(new MetaAttributePath(), root);
		querydslQuery = queryFactory.select(root);
		querydslQuery = querydslQuery.from((EntityPath) root);
	}
}
 
Example #7
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public QuerydslQueryBackend(QuerydslQueryImpl<T> queryImpl, Class<T> clazz, MetaDataObject parentMeta,
		MetaAttribute parentAttr, boolean addParentSelection) {
	this.queryImpl = queryImpl;

	JPAQueryFactory queryFactory = queryImpl.getQueryFactory();

	if (parentMeta != null) {
		parentFrom = QuerydslUtils.getEntityPath(parentMeta.getImplementationClass());
		root = QuerydslUtils.getEntityPath(clazz);

		Path joinPath = (Path) QuerydslUtils.get(parentFrom, parentAttr.getName());
		joinHelper = new JoinRegistry<>(this, queryImpl);

		joinHelper.putJoin(new MetaAttributePath(), root);

		if (addParentSelection) {
			Expression<Object> parentIdExpr = getParentIdExpression(parentMeta, parentAttr);
			querydslQuery = queryFactory.select(parentIdExpr, root);
		}
		else {
			querydslQuery = queryFactory.select(root);
		}

		querydslQuery = querydslQuery.from(parentFrom);
		if (joinPath instanceof CollectionExpression) {
			querydslQuery = querydslQuery.join((CollectionExpression) joinPath, root);
		}
		else {
			querydslQuery = querydslQuery.join((EntityPath) joinPath, root);
		}
	}
	else {
		root = QuerydslUtils.getEntityPath(clazz);
		joinHelper = new JoinRegistry<>(this, queryImpl);
		joinHelper.putJoin(new MetaAttributePath(), root);
		querydslQuery = queryFactory.select(root);
		querydslQuery = querydslQuery.from((EntityPath) root);
	}
}
 
Example #8
Source File: RSQLQueryDslPredicateConverter.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
boolean isEnumPath(Path entityClass, String property) {
	try {
		return entityClass.getClass().getDeclaredField(property).get(entityClass) instanceof EnumPath;
	} catch (Exception e) {
		return false;
	}
}
 
Example #9
Source File: RSQLQueryDslPredicateConverter.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
@SneakyThrows
StringExpression getStringExpression(Path entityClass, String property, boolean isEnumPath) {
	if (entityClass instanceof StringExpression && (property == null || property.isEmpty())) {
		return (StringExpression) entityClass;
	}
	if (isEnumPath) {
		return ((EnumPath) entityClass.getClass().getDeclaredField(property).get(entityClass)).stringValue();
	}
	return Expressions.stringPath(entityClass, property);
}
 
Example #10
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 5 votes vote down vote up
/**
 * Recursively creates a dot-separated path for the property path.
 *
 * @param path must not be {@literal null}.
 * @return
 */
private static String preparePropertyPath(Path<?> path) {

  Path<?> root = path.getRoot();

  return root == null || path.equals(root) ? path.toString()
      : path.toString().substring(root.toString().length() + 1);
}
 
Example #11
Source File: QueryDslRepositorySupportExtTest.java    From springlets with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link io.springlets.data.jpa.repository.support.QueryDslRepositorySupportExt#applyPagination(org.springframework.data.domain.Pageable, com.querydsl.jpa.JPQLQuery, java.util.Map)}.
 */
@Test
public void applyPaginationWithPageableHavingAnEmptySortShouldNotFail() {
  // Prepare
  Map<String, Path<?>[]> attributeMapping = new HashMap<>();
  when(pageable.getSort()).thenReturn(sort);
  when(sort.iterator()).thenReturn(iterator);
  when(iterator.hasNext()).thenReturn(false);

  // Exercise & verify
  support.applyPagination(pageable, null, attributeMapping);
}
 
Example #12
Source File: PageModel.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public List<OrderSpecifier> getOrderSpecifiers(){
    List<OrderSpecifier> orderSpecifiers = new ArrayList<>();
    setSort();
    if(this.getProperty()!=null){
        for(int i = 0 ; i < this.getProperty().size() ;i++){
            Path path = ExpressionUtils.path(Path.class,this.getProperty().get(i));
            OrderSpecifier orderSpecifier = new OrderSpecifier(this.toOrders(this.getDirection()).get(i),path);
            orderSpecifiers.add(orderSpecifier);
        }
    }
    return orderSpecifiers ;
}
 
Example #13
Source File: QueryDslRepositorySupportExtTest.java    From springlets with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link io.springlets.data.jpa.repository.support.QueryDslRepositorySupportExt#applyPagination(org.springframework.data.domain.Pageable, com.querydsl.jpa.JPQLQuery, java.util.Map)}.
 */
@Test
public void applyPaginationWithNullPageableShouldNotFail() {
  // Prepare
  Map<String, Path<?>[]> attributeMapping = new HashMap<>();
  when(pageable.getSort()).thenReturn(sort);
  when(sort.iterator()).thenReturn(iterator);
  when(iterator.hasNext()).thenReturn(false);

  // Exercise & verify
  support.applyPagination(null, null, attributeMapping);
}
 
Example #14
Source File: QuerydslPredicateOperationCustomizer.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets path from path spec.
 *
 * @param instance the instance
 * @return the path from path spec
 */
private Optional<Path<?>> getPathFromPathSpec(Object instance) {
	try {
		if (instance == null) {
			return Optional.empty();
		}
		Field field = FieldUtils.getDeclaredField(instance.getClass(),"path",true);
		return (Optional<Path<?>>) field.get(instance);
	}
	catch (IllegalAccessException e) {
		LOGGER.warn(e.getMessage());
	}
	return Optional.empty();
}
 
Example #15
Source File: PageModel.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public List<OrderSpecifier> getOrderSpecifiers(){
    List<OrderSpecifier> orderSpecifiers = new ArrayList<>();
    setSort();
    if(this.getProperty()!=null){
        for(int i = 0 ; i < this.getProperty().size() ;i++){
            Path path = ExpressionUtils.path(Path.class,this.getProperty().get(i));
            OrderSpecifier orderSpecifier = new OrderSpecifier(this.toOrders(this.getDirection()).get(i),path);
            orderSpecifiers.add(orderSpecifier);
        }
    }
    return orderSpecifiers ;
}
 
Example #16
Source File: QPascalCaseFooBar.java    From infobip-spring-data-querydsl with Apache License 2.0 4 votes vote down vote up
public QPascalCaseFooBar(Path<? extends QPascalCaseFooBar> path) {
    super(path.getType(), path.getMetadata(), "dbo", "PascalCaseFooBar");
    addMetadata();
}
 
Example #17
Source File: QEmbeddableImage.java    From springlets with Apache License 2.0 4 votes vote down vote up
public QEmbeddableImage(Path<? extends EmbeddableImage> path) {
  this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}
 
Example #18
Source File: QueryDslRepositorySupportExt.java    From springlets with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the given {@link Pageable} to the given {@link JPQLQuery}.
 * Allows to map the attributes to order as provided in the {@link Pageable}
 * to real entity attributes. This might be used to work with projections
 * or DTOs whose attributes don't have the same name as the entity ones.
 *
 * It allows to map to more than one entity attribute. As an example, if
 * the DTO used to create the {@link Pageable} has a fullName attribute, you
 * could map that attribute to two entity attributes: name and surname.
 * In this case, the {@link Pageable} defines an order by a fullName
 * attribute, but que query will order by name and surname instead.
 *
 * @param pageable the ordering and paging
 * @param query
 * @param attributeMapping definition of a mapping of order attribute names
 *        to real entity ones
 * @return the updated query
 */
protected JPQLQuery<T> applyPagination(Pageable pageable, JPQLQuery<T> query,
    Map<String, Path<?>[]> attributeMapping) {

  if (pageable == null) {
    return query;
  }

  Pageable mappedPageable;
  Sort sort = pageable.getSort();
  if (sort != null) {
    List<Sort.Order> mappedOrders = new ArrayList<Sort.Order>();
    for (Sort.Order order : sort) {
      if (!attributeMapping.containsKey(order.getProperty())) {
        LOG.warn(
            "The property (%1) is not included in the attributeMapping, will order "
                + "using the property as it is",
            order.getProperty());
        mappedOrders.add(order);
      } else {
        Path<?>[] paths = attributeMapping.get(order.getProperty());
        for (Path<?> path : paths) {
          Sort.Order mappedOrder =
              new Sort.Order(order.getDirection(), preparePropertyPath(path));
          mappedOrders.add(mappedOrder);
        }
      }
    }
    if (mappedOrders.isEmpty()) {
      // No properties to order by are available, so don't apply ordering and return the query
      // as it is
      return query;
    }
    mappedPageable =
        new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), new Sort(mappedOrders));
    return applyPagination(mappedPageable, query);
  } else {
    return applyPagination(pageable, query);
  }

}
 
Example #19
Source File: QuerydslQueryBackend.java    From katharsis-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Path<T> getRoot() {
	return root;
}
 
Example #20
Source File: QuerydslQueryBackend.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Path<T> getRoot() {
	return root;
}
 
Example #21
Source File: StoredProcedureQueryBuilder.java    From infobip-spring-data-querydsl with Apache License 2.0 4 votes vote down vote up
public <T> StoredProcedureQueryBuilder addInParameter(Path<T> parameter, T value) {
    Class type = parameter.getType();
    inParameters.add(new Parameter(type, parameter.getMetadata().getName(), value));
    return this;
}
 
Example #22
Source File: RSQLQueryDslPredicateConverter.java    From rsql-jpa-specification with MIT License 4 votes vote down vote up
@Override
public BooleanExpression visit(OrNode node, Path entityClass) {
	log.debug("visit(node:{},param:{})", node, entityClass);

	return node.getChildren().stream().map(n -> n.accept(this, entityClass)).collect(Collectors.reducing(BooleanExpression::or)).get();
}
 
Example #23
Source File: QuerydslUtil.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
public static OrderSpecifier<?> getSortedColumn(Order order, Path<?> parent) {
    return getSortedColumn(order, parent, "createAt");
}
 
Example #24
Source File: QCountry.java    From springdoc-openapi with Apache License 2.0 4 votes vote down vote up
public QCountry(Path<? extends Country> path) {
	super(path.getType(), path.getMetadata());
}
 
Example #25
Source File: QuerydslUtil.java    From codeway_service with GNU General Public License v3.0 4 votes vote down vote up
public static OrderSpecifier<?> getSortedColumn(Order order, Path<?> parent) {
    return getSortedColumn(order, parent, "createAt");
}
 
Example #26
Source File: RSQLQueryDslSupport.java    From rsql-jpa-specification with MIT License 4 votes vote down vote up
public static BooleanExpression toPredicate(final String rsqlQuery, final Path qClazz) {
	return toPredicate(rsqlQuery, qClazz, null);
}
 
Example #27
Source File: RSQLQueryDslPredicateConverter.java    From rsql-jpa-specification with MIT License 4 votes vote down vote up
@Override
public BooleanExpression visit(AndNode node, Path entityClass) {
	log.debug("visit(node:{},param:{})", node, entityClass);

	return node.getChildren().stream().map(n -> n.accept(this, entityClass)).collect(Collectors.reducing(BooleanExpression::and)).get();
}
 
Example #28
Source File: QCamelCaseFooBar.java    From infobip-spring-data-querydsl with Apache License 2.0 4 votes vote down vote up
public QCamelCaseFooBar(Path<? extends QCamelCaseFooBar> path) {
    super(path.getType(), path.getMetadata(), "dbo", "camelCaseFooBar");
    addMetadata();
}
 
Example #29
Source File: RSQLQueryDslPredicateConverter.java    From rsql-jpa-specification with MIT License 4 votes vote down vote up
ComparableEntityPath getComparableEntityPath(Class type, Path entityClass, String property) {
	return Expressions.comparableEntityPath(type, entityClass, property);
}
 
Example #30
Source File: QEmployeeDetail.java    From learning-code with Apache License 2.0 4 votes vote down vote up
public QEmployeeDetail(Path<? extends EmployeeDetail> path) {
    super(path.getType(), path.getMetadata());
}