Java Code Examples for org.springframework.data.repository.query.parser.PartTree

The following examples show how to use org.springframework.data.repository.query.parser.PartTree. 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
private static SqlStringAndPlaceholders buildPartTreeSqlString(PartTree tree,
		SpannerMappingContext spannerMappingContext, Class type, ParameterAccessor params) {

	SpannerPersistentEntity<?> persistentEntity = spannerMappingContext
			.getPersistentEntity(type);
	List<String> tags = new ArrayList<>();
	StringBuilder stringBuilder = new StringBuilder();

	buildSelect(persistentEntity, tree, stringBuilder, spannerMappingContext);
	buildFrom(persistentEntity, stringBuilder);
	buildWhere(tree, persistentEntity, tags, stringBuilder);
	applySort(params.getSort().isSorted() ? params.getSort() : tree.getSort(), stringBuilder, persistentEntity);
	buildLimit(tree, stringBuilder, params.getPageable());

	String selectSql = stringBuilder.toString();

	String finalSql = selectSql;

	if (tree.isCountProjection()) {
		finalSql = "SELECT COUNT(1) FROM (" + selectSql + ")";
	}
	else if (tree.isExistsProjection()) {
		finalSql = "SELECT EXISTS(" + selectSql + ")";
	}
	return new SqlStringAndPlaceholders(finalSql, tags);
}
 
Example 2
Source Project: spring-data-mybatis   Source File: PartTreeMybatisQuery.java    License: Apache License 2.0 6 votes vote down vote up
PartTreeMybatisQuery(MybatisQueryMethod method,
		SqlSessionTemplate sqlSessionTemplate) {

	super(method, sqlSessionTemplate);

	Class<?> domainClass = method.getEntityInformation().getJavaType();
	this.parameters = method.getParameters();

	boolean recreationRequired = parameters.hasDynamicProjection()
			|| parameters.potentiallySortsDynamically();

	try {

		this.tree = new PartTree(method.getName(), domainClass);

	}
	catch (Exception o_O) {
		throw new IllegalArgumentException(
				String.format("Failed to create query for method %s! %s", method,
						o_O.getMessage()),
				o_O);
	}

	this.execution = createExecution();

}
 
Example 3
private KeyValueQuery<SpelExpression> createQueryForMethodWithArgs(String methodName, Object... args)
		throws NoSuchMethodException, SecurityException {

	Class<?>[] argTypes = new Class<?>[args.length];
	if (!ObjectUtils.isEmpty(args)) {

		for (int i = 0; i < args.length; i++) {
			argTypes[i] = args[i].getClass();
		}
	}

	Method method = PersonRepository.class.getMethod(methodName, argTypes);
	doReturn(Person.class).when(metadataMock).getReturnedDomainClass(method);

	PartTree partTree = new PartTree(method.getName(), method.getReturnType());
	SpelQueryCreator creator = new SpelQueryCreator(partTree, new ParametersParameterAccessor(
			new QueryMethod(method, metadataMock, new SpelAwareProxyProjectionFactory()).getParameters(), args));

	KeyValueQuery<SpelExpression> q = creator.createQuery();
	q.getCriteria().setEvaluationContext(
			SimpleEvaluationContext.forReadOnlyDataBinding().withRootObject(args).withInstanceMethods().build());

	return q;
}
 
Example 4
private static SpelCriteria createQueryForMethodWithArgs(String methodName, Object... args) throws Exception {

		List<Class<?>> types = new ArrayList<>(args.length);

		for (Object arg : args) {
			types.add(arg.getClass());
		}

		Method method = PersonRepository.class.getMethod(methodName, types.toArray(new Class<?>[types.size()]));
		RepositoryMetadata metadata = mock(RepositoryMetadata.class);
		doReturn(method.getReturnType()).when(metadata).getReturnedDomainClass(method);

		PartTree partTree = new PartTree(method.getName(), method.getReturnType());
		SpelQueryCreator creator = new SpelQueryCreator(partTree, new ParametersParameterAccessor(
				new QueryMethod(method, metadata, new SpelAwareProxyProjectionFactory()).getParameters(), args));

		return new SpelCriteria(creator.createQuery().getCriteria(),
				SimpleEvaluationContext.forReadOnlyDataBinding().withInstanceMethods().withRootObject(args).build());
	}
 
Example 5
Source Project: sdn-rx   Source File: ReactivePartTreeNeo4jQuery.java    License: Apache License 2.0 5 votes vote down vote up
private ReactivePartTreeNeo4jQuery(
	ReactiveNeo4jOperations neo4jOperations,
	Neo4jMappingContext mappingContext,
	Neo4jQueryMethod queryMethod,
	PartTree tree
) {
	super(neo4jOperations, mappingContext, queryMethod, Neo4jQueryType.fromPartTree(tree));

	this.tree = tree;
	// Validate parts. Sort properties will be validated by Spring Data already.
	PartValidator validator = new PartValidator(queryMethod);
	this.tree.flatMap(OrPart::stream).forEach(validator::validatePart);
}
 
Example 6
Source Project: sdn-rx   Source File: CypherQueryCreator.java    License: Apache License 2.0 5 votes vote down vote up
CypherQueryCreator(Neo4jMappingContext mappingContext, Class<?> domainType, Neo4jQueryType queryType,
	PartTree tree,
	ParametersParameterAccessor actualParameters,
	List<String> includedProperties,
	Function<Object, Object> parameterConversion
) {
	super(tree, actualParameters);
	this.mappingContext = mappingContext;

	this.domainType = domainType;
	this.nodeDescription = this.mappingContext.getRequiredNodeDescription(this.domainType);

	this.queryType = queryType;

	this.formalParameters = actualParameters.getParameters().iterator();
	this.maxResults = tree.isLimiting() ? tree.getMaxResults() : null;

	this.includedProperties = includedProperties;
	this.parameterConversion = parameterConversion;

	this.pagingParameter = actualParameters.getPageable();

	AtomicInteger symbolicNameIndex = new AtomicInteger();

	propertyPathWrappers = tree.getParts().stream()
		.map(part ->
			new PropertyPathWrapper(symbolicNameIndex.getAndIncrement(),
				mappingContext.getPersistentPropertyPath(part.getProperty())))
		.collect(toList());

}
 
Example 7
Source Project: sdn-rx   Source File: PartTreeNeo4jQuery.java    License: Apache License 2.0 5 votes vote down vote up
private PartTreeNeo4jQuery(
	Neo4jOperations neo4jOperations,
	Neo4jMappingContext mappingContext,
	Neo4jQueryMethod queryMethod,
	PartTree tree
) {
	super(neo4jOperations, mappingContext, queryMethod, Neo4jQueryType.fromPartTree(tree));

	this.tree = tree;
	// Validate parts. Sort properties will be validated by Spring Data already.
	PartValidator validator = new PartValidator(queryMethod);
	this.tree.flatMap(OrPart::stream).forEach(validator::validatePart);
}
 
Example 8
Source Project: spring-data   Source File: DerivedQueryCreator.java    License: Apache License 2.0 5 votes vote down vote up
public DerivedQueryCreator(
	final MappingContext<? extends ArangoPersistentEntity<?>, ArangoPersistentProperty> context,
	final Class<?> domainClass, final PartTree tree, final ArangoParameterAccessor accessor,
	final BindParameterBinding binder, final List<String> geoFields) {
	super(tree, accessor);
	this.context = context;
	collectionName = AqlUtils.buildCollectionName(context.getPersistentEntity(domainClass).getCollection());
	this.tree = tree;
	this.accessor = accessor;
	this.geoFields = geoFields;
	this.binding = binder;
	withCollections = new HashSet<>();
}
 
Example 9
Source Project: spring-data-cosmosdb   Source File: PartTreeCosmosQuery.java    License: MIT License 5 votes vote down vote up
public PartTreeCosmosQuery(CosmosQueryMethod method, CosmosOperations operations) {
    super(method, operations);

    this.processor = method.getResultProcessor();
    this.tree = new PartTree(method.getName(), processor.getReturnedType().getDomainType());
    this.mappingContext = operations.getConverter().getMappingContext();
}
 
Example 10
Source Project: spring-data-cosmosdb   Source File: PartTreeReactiveCosmosQuery.java    License: MIT License 5 votes vote down vote up
public PartTreeReactiveCosmosQuery(ReactiveCosmosQueryMethod method, ReactiveCosmosOperations operations) {
    super(method, operations);

    this.processor = method.getResultProcessor();
    this.tree = new PartTree(method.getName(), processor.getReturnedType().getDomainType());
    this.mappingContext = operations.getConverter().getMappingContext();
}
 
Example 11
Source Project: spring-cloud-gcp   Source File: PartTreeDatastoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param queryMethod the metadata for this query method.
 * @param datastoreTemplate used to execute the given query.
 * @param datastoreMappingContext used to provide metadata for mapping results to objects.
 * @param entityType the result domain type.
 * @param projectionFactory the projection factory that is used to get projection information.
 */
public PartTreeDatastoreQuery(DatastoreQueryMethod queryMethod,
							DatastoreOperations datastoreTemplate,
		DatastoreMappingContext datastoreMappingContext, Class<T> entityType, ProjectionFactory projectionFactory) {
	super(queryMethod, datastoreTemplate, datastoreMappingContext, entityType);
	this.tree = new PartTree(queryMethod.getName(), entityType);
	this.datastorePersistentEntity = this.datastoreMappingContext
			.getPersistentEntity(this.entityType);

	this.projectionFactory = projectionFactory;
	validateAndSetFilterParts();
}
 
Example 12
/**
 * Executes a PartTree-based query.
 * @param type the type of the underlying entity
 * @param tree the parsed metadata of the query
 * @param parameterAccessor the parameters of this specific query
 * @param queryMethodParamsMetadata parameter metadata from Query Method
 * @param spannerTemplate used to execute the query
 * @param spannerMappingContext used to get metadata about the entity type
 * @param <T> the type of the underlying entity
 * @return list of entities.
 */
public static <T> List<T> executeQuery(Class<T> type, PartTree tree, ParameterAccessor parameterAccessor,
		Parameter[] queryMethodParamsMetadata,
		SpannerTemplate spannerTemplate,
		SpannerMappingContext spannerMappingContext) {
	SqlStringAndPlaceholders sqlStringAndPlaceholders = buildPartTreeSqlString(tree, spannerMappingContext, type, parameterAccessor);
	Map<String, Parameter> paramMetadataMap = preparePartTreeSqlTagParameterMap(queryMethodParamsMetadata,
			sqlStringAndPlaceholders);
	Object[] params = StreamSupport.stream(parameterAccessor.spliterator(), false).toArray();
	return spannerTemplate.query(type, buildStatementFromSqlWithArgs(
			sqlStringAndPlaceholders.getSql(), sqlStringAndPlaceholders.getPlaceholders(), null,
			spannerTemplate.getSpannerEntityProcessor().getWriteConverter(), params, paramMetadataMap), null);
}
 
Example 13
private static void buildSelect(
		SpannerPersistentEntity<?> spannerPersistentEntity, PartTree tree,
		StringBuilder stringBuilder, SpannerMappingContext mappingContext) {
	stringBuilder.append("SELECT ").append(tree.isDistinct() ? "DISTINCT " : "")
			.append(getColumnsStringForSelect(spannerPersistentEntity, mappingContext,
					!(tree.isExistsProjection() || tree.isCountProjection()))).append(" ");
}
 
Example 14
private static void buildLimit(PartTree tree, StringBuilder stringBuilder, Pageable pageable) {
	if (tree.isExistsProjection()) {
		stringBuilder.append(" LIMIT 1");
	}
	else if (pageable.isPaged()) {
		stringBuilder.append(" LIMIT ").append(pageable.getPageSize())
				.append(" OFFSET ").append(pageable.getOffset());
	}
	else if (tree.isLimiting()) {
		stringBuilder.append(" LIMIT ").append(tree.getMaxResults());
	}
}
 
Example 15
Source Project: spring-cloud-gcp   Source File: PartTreeFirestoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
public PartTreeFirestoreQuery(FirestoreQueryMethod queryMethod, FirestoreReactiveOperations reactiveOperations,
		FirestoreMappingContext mappingContext, FirestoreClassMapper classMapper) {
	this.queryMethod = queryMethod;
	this.reactiveOperations = reactiveOperations;
	ReturnedType returnedType = queryMethod.getResultProcessor().getReturnedType();
	this.tree = new PartTree(queryMethod.getName(), returnedType.getDomainType());
	this.persistentEntity = mappingContext.getPersistentEntity(returnedType.getDomainType());
	this.mappingContext = mappingContext;
	this.classMapper = classMapper;
	validate();
}
 
Example 16
Source Project: spring-cloud-gcp   Source File: PartTreeFirestoreQuery.java    License: Apache License 2.0 5 votes vote down vote up
private void validate() {
	List parts = this.tree.get().collect(Collectors.toList());
	if (parts.size() > 1 && parts.get(0) instanceof PartTree.OrPart) {
			throw new FirestoreDataException(
					"Cloud Firestore doesn't support 'OR' (method name: " + this.getQueryMethod().getName() + ")");
	}
	List<String> unsupportedParts = this.tree.getParts().stream()
			.filter(part -> !isSupportedPart(part.getType()))
			.map(part -> part.getType().toString())
			.collect(Collectors.toList());
	if (!unsupportedParts.isEmpty()) {
		throw new FirestoreDataException("Unsupported predicate keywords: " + unsupportedParts
				+ " in " + this.getQueryMethod().getName());
	}
}
 
Example 17
Source Project: spring-data-ebean   Source File: PartTreeEbeanQuery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link PartTreeEbeanQuery}.
 *
 * @param method      must not be {@literal null}.
 * @param ebeanServer must not be {@literal null}.
 */
public PartTreeEbeanQuery(EbeanQueryMethod method, EbeanServer ebeanServer) {
    super(method, ebeanServer);

    this.domainClass = method.getEntityInformation().getJavaType();
    this.tree = new PartTree(method.getName(), domainClass);
    this.parameters = (DefaultParameters) method.getParameters();
    this.queryPreparer = new QueryPreparer(ebeanServer);
}
 
Example 18
Source Project: spring-data-ebean   Source File: EbeanQueryCreator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link EbeanQueryCreator}.
 *
 * @param tree           must not be {@literal null}.
 * @param type           must not be {@literal null}.
 * @param expressionList must not be {@literal null}.
 * @param provider       must not be {@literal null}.
 */
public EbeanQueryCreator(PartTree tree, ReturnedType type, ExpressionList expressionList,
                         ParameterMetadataProvider provider) {
    super(tree);
    this.tree = tree;

    this.root = expressionList;
    this.provider = provider;
    this.returnedType = type;
}
 
Example 19
Source Project: spring-vault   Source File: VaultQueryCreatorUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, String value) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example 20
Source Project: spring-vault   Source File: VaultQueryCreatorUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, List<String> value) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", List.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value }), this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example 21
Source Project: spring-vault   Source File: VaultQueryCreatorUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
VaultQuery createQuery(String methodName, String value, String anotherValue) {

		DefaultParameters defaultParameters = new DefaultParameters(
				ReflectionUtils.findMethod(dummy.class, "someUnrelatedMethod", String.class, String.class));

		PartTree partTree = new PartTree(methodName, Credentials.class);
		VaultQueryCreator queryCreator = new VaultQueryCreator(partTree,
				new ParametersParameterAccessor(defaultParameters, new Object[] { value, anotherValue }),
				this.mappingContext);

		return queryCreator.createQuery().getCriteria();
	}
 
Example 22
/**
 * <p>
 * Determine if the arguments to the method need reordered.
 * </P>
 * <p>
 * For searches such as {@code findBySomethingNotNull} there may be more parts than parameters needed to be bound to
 * them.
 * </P>
 *
 * @param partTree           Query parts
 * @param bindableParameters Parameters expected
 */
@SuppressWarnings("unchecked")
private void prepareRearrange(final PartTree partTree, final Parameters<?, ?> bindableParameters) {

    this.isRearrangeRequired = false;
    if (partTree == null || bindableParameters == null) {
        return;
    }

    List<String> queryParams = new ArrayList<>();
    List<String> methodParams = new ArrayList<>();

    for (Part part : partTree.getParts()) {
        queryParams.add(part.getProperty().getSegment());
    }

    Iterator<Parameter> bindableParameterIterator = (Iterator<Parameter>) bindableParameters.iterator();
    while (bindableParameterIterator.hasNext()) {
        Parameter parameter = bindableParameterIterator.next();
        parameter.getName().ifPresent(methodParams::add);
    }

    this.rearrangeIndex = new int[queryParams.size()];

    String[] paramsExpected = queryParams.toArray(new String[0]);
    String[] paramsProvided = methodParams.toArray(new String[0]);

    for (int i = 0; i < this.rearrangeIndex.length; i++) {
        this.rearrangeIndex[i] = i;

        for (int j = 0; j < paramsProvided.length; j++) {
            if (paramsProvided[j] != null && paramsProvided[j].equals(paramsExpected[i])) {
                this.rearrangeIndex[i] = j;
                this.isRearrangeRequired = true;
            }
        }
    }
}
 
Example 23
/**
 * Creates a new {@link HazelcastQueryCreator} for the given {@link PartTree}.
 *
 * @param tree must not be {@literal null}.
 */
public HazelcastQueryCreator(PartTree tree) {
    super(tree);

    final Integer maxResults = tree.getMaxResults();
    if (tree.isLimiting() && maxResults != null && maxResults > 0) {
        this.limit = maxResults;
    } else {
        this.limit = 0;
    }
}
 
Example 24
/**
 * Creates a new {@link HazelcastQueryCreator} for the given {@link PartTree} and {@link ParameterAccessor}. The
 * latter is used to hand actual parameter values into the callback methods as well as to apply dynamic sorting via a
 * {@link Sort} parameter.
 *
 * @param tree       must not be {@literal null}.
 * @param parameters can be {@literal null}.
 */
public HazelcastQueryCreator(PartTree tree, ParameterAccessor parameters) {
    super(tree, parameters);

    final Integer maxResults = tree.getMaxResults();
    if (tree.isLimiting() && maxResults != null && maxResults > 0) {
        this.limit = maxResults;
    } else {
        this.limit = 0;
    }
}
 
Example 25
/**
 * Create a {@link KeyValueQuery} given {@link ParameterAccessor}.
 *
 * @param accessor must not be {@literal null}.
 * @return the {@link KeyValueQuery}.
 */
public KeyValueQuery<?> createQuery(ParameterAccessor accessor) {

	PartTree tree = new PartTree(getQueryMethod().getName(), getQueryMethod().getEntityInformation().getJavaType());

	AbstractQueryCreator<? extends KeyValueQuery<?>, ?> queryCreator = queryCreatorFactory.queryCreatorFor(tree,
			accessor);

	KeyValueQuery<?> query = queryCreator.createQuery();

	if (tree.isLimiting()) {
		query.setRows(tree.getMaxResults());
	}
	return query;
}
 
Example 26
@Override
public AbstractQueryCreator<KeyValueQuery<?>, ?> queryCreatorFor(PartTree partTree, ParameterAccessor accessor) {

	Assert.state(constructor != null,
			() -> String.format("No constructor (PartTree, ParameterAccessor) could be found on type %s!", type));
	return (AbstractQueryCreator<KeyValueQuery<?>, ?>) BeanUtils.instantiateClass(constructor, partTree, accessor);
}
 
Example 27
public AbstractDynamoDBQueryCreator(PartTree tree, ParameterAccessor parameterAccessor,
		DynamoDBEntityInformation<T, ID> entityMetadata, DynamoDBOperations dynamoDBOperations) {
	super(tree, parameterAccessor);
	this.entityMetadata = entityMetadata;
	this.dynamoDBOperations = dynamoDBOperations;

}
 
Example 28
public DynamoDBCountQueryCreator(PartTree tree,
		ParameterAccessor parameterAccessor,
		DynamoDBEntityInformation<T, ID> entityMetadata,
		DynamoDBOperations dynamoDBOperations,boolean pageQuery) {
	super(tree, parameterAccessor, entityMetadata, dynamoDBOperations);
	this.pageQuery = pageQuery;

}
 
Example 29
Source Project: spring-data-simpledb   Source File: PartTreeConverter.java    License: MIT License 5 votes vote down vote up
/**
 * Convert a {@link PartTree} into a where query alike to the one present in the
 * {@link Query}'s where property.  
 */
public static String toIndexedQuery(final PartTree tree) {
	final StringBuilder result = new StringBuilder();
	
	final Iterator<OrPart> orIt = tree.iterator();
	while(orIt.hasNext()) {
		
		final OrPart orPart = orIt.next();
		
		final Iterator<Part> partIt = orPart.iterator();
		while(partIt.hasNext()) {
			final Part part = partIt.next();
			
			result.append(" " + part.getProperty().getSegment() + " ");
			result.append(convertOperator(part.getType()));
			
			if(partIt.hasNext()) {
				result.append(" AND ");
			}
		}
		
		if(orIt.hasNext()) {
			result.append(" OR ");
		}
	}
	
	return StringUtil.removeExtraSpaces(result.toString());
}
 
Example 30
Source Project: spring-data-simpledb   Source File: SimpleDbPartTreeQueryMethod.java    License: MIT License 5 votes vote down vote up
public SimpleDbPartTreeQueryMethod(Method method, RepositoryMetadata metadata, SimpleDbDomain simpleDbDomain) {
	super(method, metadata, simpleDbDomain);
	
	final String domainName = simpleDbDomain.getDomain(metadata.getDomainType());
	final SimpleDbEntityInformation<?, ?> entityInformation = SimpleDbEntityInformationSupport.getMetadata(metadata.getDomainType(), domainName);
	
	whereExpression = PartTreeConverter.toIndexedQuery(new PartTree(method.getName(), entityInformation.getJavaType()));
}