org.springframework.data.repository.query.ParameterAccessor Java Examples

The following examples show how to use org.springframework.data.repository.query.ParameterAccessor. 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: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private Slice executeSliceQuery(Object[] parameters) {
	StructuredQuery.Builder builder = getEntityOrProjectionQueryBuilder()
			.setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery query = applyQueryBody(parameters, builder, false, false, null);
	DatastoreResultsIterable<?> resultList = this.datastoreOperations.queryKeysOrEntities(query, this.entityType);

	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);

	Pageable pageable = DatastorePageable.from(paramAccessor.getPageable(), resultList.getCursor(), null);

	EntityQuery.Builder builderNext = newEntityQueryBuilder().setKind(this.datastorePersistentEntity.kindName());
	StructuredQuery queryNext = applyQueryBody(parameters, builderNext, false, true, resultList.getCursor());
	Iterable nextResult = this.datastoreOperations.query(queryNext, x -> x);

	List<Object> result =
					StreamSupport.stream(resultList.spliterator(), false).collect(Collectors.toList());

	return (Slice) this.processRawObjectForProjection(
			new SliceImpl(result, pageable, nextResult.iterator().hasNext()));
}
 
Example #2
Source File: SqlSpannerQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Override
public List executeRawResult(Object[] parameters) {

	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);
	Object[] params = StreamSupport.stream(paramAccessor.spliterator(), false).toArray();

	QueryTagValue queryTagValue = new QueryTagValue(getParamTags(), parameters,
					params, resolveEntityClassNames(this.sql, this.spannerMappingContext));

	resolveSpELTags(queryTagValue);

	return this.isDml
			? Collections.singletonList(
					this.spannerTemplate.executeDmlStatement(buildStatementFromQueryAndTags(queryTagValue)))
			: executeReadSql(paramAccessor.getPageable(), paramAccessor.getSort(), queryTagValue);
}
 
Example #3
Source File: FreemarkerTemplateQuery.java    From spring-data-jpa-extra with Apache License 2.0 6 votes vote down vote up
@Override
protected Query doCreateQuery(Object[] values) {
    String nativeQuery = getQuery(values);
    JpaParameters parameters = getQueryMethod().getParameters();
    ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
    String sortedQueryString = QueryUtils
            .applySorting(nativeQuery, accessor.getSort(), QueryUtils.detectAlias(nativeQuery));
    Query query = bind(createJpaQuery(sortedQueryString), values);
    if (parameters.hasPageableParameter()) {
        Pageable pageable = (Pageable) (values[parameters.getPageableIndex()]);
        if (pageable != null) {
            query.setFirstResult((int) pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }
    }
    return query;
}
 
Example #4
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: PartTreeSpannerQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Override
protected List executeRawResult(Object[] parameters) {
	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(),
			parameters);
	if (isCountOrExistsQuery()) {
		return SpannerStatementQueryExecutor.executeQuery(
				(struct) -> isCountQuery() ? struct.getLong(0) : struct.getBoolean(0),
				this.entityType, this.tree, paramAccessor, getQueryMethod().getMethod().getParameters(),
				this.spannerTemplate,
				this.spannerMappingContext);
	}
	if (this.tree.isDelete()) {
		return this.spannerTemplate
				.performReadWriteTransaction(getDeleteFunction(parameters));
	}
	return SpannerStatementQueryExecutor.executeQuery(this.entityType, this.tree,
			paramAccessor, getQueryMethod().getMethod().getParameters(), this.spannerTemplate,
			this.spannerMappingContext);
}
 
Example #6
Source File: PartTreeSpannerQuery.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private Function<SpannerTemplate, List> getDeleteFunction(Object[] parameters) {
	return (transactionTemplate) -> {
		ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(),
				parameters);
		List<T> entitiesToDelete = SpannerStatementQueryExecutor
				.executeQuery(this.entityType, this.tree, paramAccessor, getQueryMethod().getMethod().getParameters(),
						transactionTemplate, this.spannerMappingContext);
		transactionTemplate.deleteAll(entitiesToDelete);

		List result = null;
		if (this.queryMethod.isCollectionQuery()) {
			result = entitiesToDelete;
		}
		else if (this.queryMethod.getReturnedObjectType() != void.class) {
			result = Collections.singletonList(entitiesToDelete.size());
		}
		return result;
	};
}
 
Example #7
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #8
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(Object[] parameters) {

	ParameterAccessor accessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);
	KeyValueQuery<?> query = prepareQuery(parameters);
	ResultProcessor processor = queryMethod.getResultProcessor().withDynamicProjection(accessor);

	return processor.processResult(doExecute(parameters, query));
}
 
Example #9
Source File: HazelcastQueryCreator.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #10
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
@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 #11
Source File: AbstractDynamoDBQueryCreator.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
public AbstractDynamoDBQueryCreator(PartTree tree, ParameterAccessor parameterAccessor,
		DynamoDBEntityInformation<T, ID> entityMetadata, DynamoDBOperations dynamoDBOperations) {
	super(tree, parameterAccessor);
	this.entityMetadata = entityMetadata;
	this.dynamoDBOperations = dynamoDBOperations;

}
 
Example #12
Source File: AbstractEbeanQueryExecution.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Object doExecute(final AbstractEbeanQuery repositoryQuery, final Object[] values) {
    ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
    EbeanQueryWrapper createQuery = repositoryQuery.createQuery(values);
    return createQuery.findPage(accessor.getPageable());
}
 
Example #13
Source File: PartTreeFirestoreQuery.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(Object[] parameters) {
	StructuredQuery.Builder builder = createBuilderWithFilter(parameters);

	// Handle Pageable parameters.
	if (!getQueryMethod().getParameters().isEmpty()) {
		ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(),
				parameters);
		Pageable pageable = paramAccessor.getPageable();
		if (pageable != null && pageable.isPaged()) {
			builder.setOffset((int) Math.min(Integer.MAX_VALUE, pageable.getOffset()));
			builder.setLimit(Int32Value.newBuilder().setValue(pageable.getPageSize()));
		}

		Sort sort = paramAccessor.getSort();
		if (sort != null) {
			builder.addAllOrderBy(createFirestoreSortOrders(sort));
		}
	}

	if (this.tree.isCountProjection()) {
		return this.reactiveOperations.count(this.persistentEntity.getType(), builder);
	}
	else {
		return this.reactiveOperations.execute(builder, this.persistentEntity.getType());
	}
}
 
Example #14
Source File: DynamoDBCountQueryCreator.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
public DynamoDBCountQueryCreator(PartTree tree,
		ParameterAccessor parameterAccessor,
		DynamoDBEntityInformation<T, ID> entityMetadata,
		DynamoDBOperations dynamoDBOperations,boolean pageQuery) {
	super(tree, parameterAccessor, entityMetadata, dynamoDBOperations);
	this.pageQuery = pageQuery;

}
 
Example #15
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #16
Source File: AbstractDynamoDBQuery.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(AbstractDynamoDBQuery<T, ID> dynamoDBQuery, Object[] values) {

	ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
	Pageable pageable = accessor.getPageable();
	Query<T> query = dynamoDBQuery.doCreateQueryWithPermissions(values);

	List<T> results = query.getResultList();
	return createPage(results, pageable,dynamoDBQuery,values);
}
 
Example #17
Source File: AbstractDynamoDBQuery.java    From spring-data-dynamodb with Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(AbstractDynamoDBQuery<T, ID> dynamoDBQuery, Object[] values) {

	ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
	Pageable pageable = accessor.getPageable();
	Query<T> query = dynamoDBQuery.doCreateQueryWithPermissions(values);
	List<T> results = query.getResultList();
	return createSlice(results, pageable);
}
 
Example #18
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(Object[] parameters) {
	Class<?> returnedObjectType = getQueryMethod().getReturnedObjectType();
	if (isPageQuery()) {
		ExecutionResult executionResult = (ExecutionResult) runQuery(parameters, returnedObjectType, List.class,
				false);

		List<?> resultEntries = (List) executionResult.getPayload();

		ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(),
				parameters);

		Pageable pageableParam = paramAccessor.getPageable();

		Long totalCount;
		if (pageableParam instanceof DatastorePageable) {
			Long previousCount = ((DatastorePageable) pageableParam).getTotalCount();
			Assert.notNull(previousCount, "Previous total count can not be null.");

			totalCount = ((DatastorePageable) pageableParam).getTotalCount();
		}
		else {
			totalCount = (Long) runQuery(parameters, Long.class, null, true);
		}

		Pageable pageable = DatastorePageable.from(pageableParam, executionResult.getCursor(), totalCount);

		return new PageImpl<>(resultEntries, pageable, totalCount);
	}

	if (isSliceQuery()) {
		return executeSliceQuery(parameters);
	}

	Object result = runQuery(parameters, returnedObjectType,
			((DatastoreQueryMethod) getQueryMethod()).getCollectionReturnType(), false);

	result = result instanceof PartTreeDatastoreQuery.ExecutionResult ? ((ExecutionResult) result).getPayload()
			: result;
	if (result == null && ((DatastoreQueryMethod) getQueryMethod()).isOptionalReturnType()) {
		return Optional.empty();
	}
	return result;
}
 
Example #19
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 4 votes vote down vote up
ConstructorCachingQueryCreatorFactory(Class<? extends AbstractQueryCreator<?, ?>> type) {

			this.type = type;
			this.constructor = ClassUtils.getConstructorIfAvailable(type, PartTree.class, ParameterAccessor.class);
		}
 
Example #20
Source File: DynamoDBQueryCreator.java    From spring-data-dynamodb with Apache License 2.0 4 votes vote down vote up
public DynamoDBQueryCreator(PartTree tree,
		ParameterAccessor parameterAccessor,
		DynamoDBEntityInformation<T, ID> entityMetadata,
		DynamoDBOperations dynamoDBOperations) {
	super(tree, parameterAccessor, entityMetadata, dynamoDBOperations);
}
 
Example #21
Source File: VaultPartTreeQuery.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Override
public VaultQueryCreator queryCreatorFor(PartTree partTree, ParameterAccessor accessor) {
	return new VaultQueryCreator(partTree, accessor, this.mappingContext);
}
 
Example #22
Source File: GqlDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
ParsedQueryWithTagsAndValues(List<String> initialTags, Object[] rawParams) {
	this.params = Arrays.stream(rawParams).filter(e -> !(e instanceof Pageable || e instanceof Sort))
			.collect(Collectors.toList());
	this.rawParams = rawParams;
	this.tagsOrdered = new ArrayList<>(initialTags);

	SpelEvaluator spelEvaluator = GqlDatastoreQuery.this.evaluatingSpelQueryContext.parse(
			GqlDatastoreQuery.this.gqlResolvedEntityClassName,
			GqlDatastoreQuery.this.queryMethod.getParameters());
	Map<String, Object> results = spelEvaluator.evaluate(this.rawParams);
	this.finalGql = spelEvaluator.getQueryString();

	for (Map.Entry<String, Object> entry : results.entrySet()) {
		this.params.add(entry.getValue());
		// Cloud Datastore requires the tag name without the @
		this.tagsOrdered.add(entry.getKey().substring(1));
	}

	ParameterAccessor paramAccessor =
			new ParametersParameterAccessor(getQueryMethod().getParameters(), rawParams);
	Sort sort = paramAccessor.getSort();

	this.finalGql = addSort(this.finalGql, sort);

	this.noLimitQuery = this.finalGql;
	Pageable pageable = paramAccessor.getPageable();
	if (!pageable.equals(Pageable.unpaged())) {
		this.finalGql += LIMIT_CLAUSE;
		this.tagsOrdered.add(LIMIT_TAG_NAME);
		this.limitPosition = this.params.size();
		this.params.add(pageable.getPageSize());

		this.finalGql += OFFSET_CLAUSE;
		this.tagsOrdered.add(OFFSET_TAG_NAME);
		this.cursorPosition = this.params.size();
		if (pageable instanceof DatastorePageable && ((DatastorePageable) pageable).toCursor() != null) {
			this.params.add(((DatastorePageable) pageable).toCursor());
		}
		else {
			this.params.add(pageable.getOffset());
		}
	}
}
 
Example #23
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
private StructuredQuery applyQueryBody(Object[] parameters,
		Builder builder, boolean total, boolean singularResult, Cursor cursor) {
	ParameterAccessor paramAccessor = new ParametersParameterAccessor(getQueryMethod().getParameters(), parameters);
	if (this.tree.hasPredicate()) {
		applySelectWithFilter(parameters, builder);
	}

	Pageable pageable = paramAccessor.getPageable();
	Integer limit = null;
	Integer offset = null;
	if (singularResult || this.tree.isExistsProjection()) {
		limit = 1;
	}
	else if (this.tree.isLimiting()) {
		limit = this.tree.getMaxResults();
	}

	if (!singularResult && !total && pageable.isPaged()) {
		limit = pageable.getPageSize();
	}

	Sort sort = this.tree.getSort();
	if (getQueryMethod().getParameters().hasPageableParameter()) {
		sort = sort.and(pageable.getSort());
	}
	if (getQueryMethod().getParameters().hasSortParameter()) {
		sort = sort.and(paramAccessor.getSort());
	}

	if (pageable.isPaged() && !total) {
		offset = (int) pageable.getOffset();
	}

	Cursor cursorToApply = null;
	if (cursor != null) {
		cursorToApply = cursor;
	}
	else if (pageable instanceof DatastorePageable) {
		cursorToApply = ((DatastorePageable) pageable).toCursor();
	}
	DatastoreTemplate.applyQueryOptions(
			builder, new DatastoreQueryOptions.Builder().setLimit(limit).setOffset(offset).setSort(sort)
					.setCursor(cursorToApply).build(),
			this.datastorePersistentEntity);
	return builder.build();
}
 
Example #24
Source File: Neo4jQuerySupport.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
protected final ResultProcessor getResultProcessor(ParameterAccessor parameterAccessor) {
	return queryMethod.getResultProcessor().withDynamicProjection(parameterAccessor);
}
 
Example #25
Source File: SpelQueryCreator.java    From spring-data-keyvalue with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new {@link SpelQueryCreator} for the given {@link PartTree} and {@link ParameterAccessor}.
 *
 * @param tree must not be {@literal null}.
 * @param parameters must not be {@literal null}.
 */
public SpelQueryCreator(PartTree tree, ParameterAccessor parameters) {

	super(tree, parameters);

	this.expression = toPredicateExpression(tree);
}
 
Example #26
Source File: VaultQueryCreator.java    From spring-vault with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new {@link VaultQueryCreator} given {@link PartTree} and
 * {@link ParameterAccessor}.
 * @param tree must not be {@literal null}.
 * @param parameters must not be {@literal null}.
 * @param mappingContext must not be {@literal null}.
 */
public VaultQueryCreator(PartTree tree, ParameterAccessor parameters,
		MappingContext<VaultPersistentEntity<?>, VaultPersistentProperty> mappingContext) {

	super(tree, parameters);
	this.mappingContext = mappingContext;
}
 
Example #27
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 3 votes vote down vote up
/**
 * Executes a PartTree-based query and applies a custom row-mapping function to the
 * result.
 * @param rowFunc the function to apply to each row of the result.
 * @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 <A> the type to which to convert Struct params
 * @param <T> the type of the underlying entity on which to query
 * @return list of objects mapped using the given function.
 */
public static <A, T> List<A> executeQuery(Function<Struct, A> rowFunc, 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(rowFunc, buildStatementFromSqlWithArgs(
			sqlStringAndPlaceholders.getSql(), sqlStringAndPlaceholders.getPlaceholders(), null,
			spannerTemplate.getSpannerEntityProcessor().getWriteConverter(), params, paramMetadataMap), null);
}
 
Example #28
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 votes vote down vote up
T queryCreatorFor(PartTree partTree, ParameterAccessor accessor);