Java Code Examples for com.querydsl.core.types.Path

The following examples show how to use com.querydsl.core.types.Path. These examples are extracted from open source projects. 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
/***
 * 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 2
Source Project: springlets   Source File: QueryDslRepositorySupportExt.java    License: 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 3
/**
 * 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 4
/**
 * 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 5
Source Project: ZTuoExchange_framework   Source File: PageModel.java    License: 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 6
/**
 * 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 7
Source Project: ZTuoExchange_framework   Source File: PageModel.java    License: 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 8
Source Project: rsql-jpa-specification   Source File: RSQLQueryDslSupport.java    License: 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 9
@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
boolean isEnumPath(Path entityClass, String property) {
	try {
		return entityClass.getClass().getDeclaredField(property).get(entityClass) instanceof EnumPath;
	} catch (Exception e) {
		return false;
	}
}
 
Example 11
Source Project: crnk-framework   Source File: QuerydslQueryBackend.java    License: 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 12
Source Project: katharsis-framework   Source File: QuerydslQueryBackend.java    License: 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 13
Source Project: springlets   Source File: QueryDslRepositorySupportExt.java    License: 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 14
/**
 * 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 15
/**
 * 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 16
Source Project: codeway_service   Source File: QuerydslUtil.java    License: 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 17
Source Project: springdoc-openapi   Source File: QCountry.java    License: Apache License 2.0 4 votes vote down vote up
public QCountry(Path<? extends Country> path) {
	super(path.getType(), path.getMetadata());
}
 
Example 18
Source Project: codeway_service   Source File: QuerydslUtil.java    License: 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 19
Source Project: rsql-jpa-specification   Source File: RSQLQueryDslSupport.java    License: MIT License 4 votes vote down vote up
public static BooleanExpression toPredicate(final String rsqlQuery, final Path qClazz) {
	return toPredicate(rsqlQuery, qClazz, null);
}
 
Example 20
@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 21
@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 22
ComparableEntityPath getComparableEntityPath(Class type, Path entityClass, String property) {
	return Expressions.comparableEntityPath(type, entityClass, property);
}
 
Example 23
Source Project: learning-code   Source File: QEmployeeDetail.java    License: Apache License 2.0 4 votes vote down vote up
public QEmployeeDetail(Path<? extends EmployeeDetail> path) {
    super(path.getType(), path.getMetadata());
}
 
Example 24
Source Project: learning-code   Source File: QEmployee.java    License: Apache License 2.0 4 votes vote down vote up
public QEmployee(Path<? extends Employee> path) {
    this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}
 
Example 25
Source Project: learning-code   Source File: QJob.java    License: Apache License 2.0 4 votes vote down vote up
public QJob(Path<? extends Job> path) {
    super(path.getType(), path.getMetadata());
}
 
Example 26
public QEntityWithSchema(Path<? extends QEntityWithSchema> path) {
    super(path.getType(), path.getMetadata(), "foo", "EntityWithSchema");
    addMetadata();
}
 
Example 27
public QPascalCaseFooBar(Path<? extends QPascalCaseFooBar> path) {
    super(path.getType(), path.getMetadata(), "dbo", "PascalCaseFooBar");
    addMetadata();
}
 
Example 28
public QCamelCaseFooBar(Path<? extends QCamelCaseFooBar> path) {
    super(path.getType(), path.getMetadata(), "dbo", "camelCaseFooBar");
    addMetadata();
}
 
Example 29
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 30
Source Project: crnk-framework   Source File: QuerydslQueryBackend.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Path<T> getRoot() {
	return root;
}