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

The following examples show how to use org.springframework.data.repository.query.parser.PartTree. 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: 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 #2
Source File: PartTreeMybatisQuery.java    From spring-data-mybatis with 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
Source File: SpelQueryEngineUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: SpelQueryCreatorUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
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 #5
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 #6
Source File: PartTreeEbeanQuery.java    From spring-data-ebean with 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 #7
Source File: EbeanQueryCreator.java    From spring-data-ebean with 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 #8
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with 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 #9
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with 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 #10
Source File: VaultQueryCreatorUnitTests.java    From spring-vault with 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 #11
Source File: HazelcastPartTreeQuery.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * <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 #12
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}.
 *
 * @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 #13
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 #14
Source File: PartTreeConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test(expected = MappingException.class) 
public void shoud_fail_for_unsupported_operator() {
	final String methodName = "readByAgeEndsWith";
	final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
	
	PartTreeConverter.toIndexedQuery(tree);
}
 
Example #15
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 #16
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 #17
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 #18
Source File: PartTreeConverter.java    From spring-data-simpledb with 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 #19
Source File: SimpleDbPartTreeQueryMethod.java    From spring-data-simpledb with 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()));
}
 
Example #20
Source File: PartTreeConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test
public void should_create_corect_query_for_simple_property() {
	final String methodName = "findByItemName";
	final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
	
	final String query = PartTreeConverter.toIndexedQuery(tree);
	
	final String expected = " itemName = ? ";
	
	assertEquals(expected, query);
}
 
Example #21
Source File: PartTreeConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test
public void should_create_corect_query_for_between() {
	final String methodName = "readByAgeBetween";
	final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
	
	final String query = PartTreeConverter.toIndexedQuery(tree);
	
	final String expected = " age BETWEEN ? and ? ";
	
	assertEquals(expected, query);
}
 
Example #22
Source File: PartTreeConverterTest.java    From spring-data-simpledb with MIT License 5 votes vote down vote up
@Test
public void should_create_corect_query_for_complex_operators() {
	final String methodName = "getByItemNameLikeOrAgeGreaterThanAndAgeLessThan";
	final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class);
	
	final String query = PartTreeConverter.toIndexedQuery(tree);
	
	final String expected = " itemName LIKE ? OR age > ? AND age < ? ";
	
	assertEquals(expected, query);
}
 
Example #23
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 #24
Source File: DerivedQueryCreator.java    From spring-data with 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 #25
Source File: PartTreeDatastoreQuery.java    From spring-cloud-gcp with 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 #26
Source File: PartTreeReactiveCosmosQuery.java    From spring-data-cosmosdb with 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 #27
Source File: PartTreeCosmosQuery.java    From spring-data-cosmosdb with 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 #28
Source File: PartTreeNeo4jQuery.java    From sdn-rx with 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 #29
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: SpannerStatementQueryExecutor.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
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());
	}
}