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

The following examples show how to use org.springframework.data.repository.query.QueryMethodEvaluationContextProvider. 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: MybatisQueryLookupStrategy.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
public static QueryLookupStrategy create(SqlSessionTemplate sqlSessionTemplate,
		Key key, QueryMethodEvaluationContextProvider evaluationContextProvider) {

	Assert.notNull(sqlSessionTemplate, "SqlSessionTemplate must not be null!");
	Assert.notNull(evaluationContextProvider,
			"EvaluationContextProvider must not be null!");

	switch (key != null ? key : Key.CREATE_IF_NOT_FOUND) {
	case CREATE:
		return new CreateQueryLookupStrategy(sqlSessionTemplate);
	case USE_DECLARED_QUERY:
		return new DeclaredQueryLookupStrategy(sqlSessionTemplate,
				evaluationContextProvider);
	case CREATE_IF_NOT_FOUND:
		return new CreateIfNotFoundQueryLookupStrategy(sqlSessionTemplate,
				new CreateQueryLookupStrategy(sqlSessionTemplate),
				new DeclaredQueryLookupStrategy(sqlSessionTemplate,
						evaluationContextProvider));
	default:
		throw new IllegalArgumentException(
				String.format("Unsupported query lookup strategy %s!", key));
	}
}
 
Example #2
Source File: KeyValuePartTreeQueryUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Test // DATAKV-142
@SuppressWarnings({ "unchecked", "rawtypes" })
public void shouldApplyPageableParameterToCollectionQuery() throws SecurityException, NoSuchMethodException {

	when(metadataMock.getDomainType()).thenReturn((Class) Person.class);
	when(metadataMock.getReturnedDomainClass(any(Method.class))).thenReturn((Class) Person.class);

	QueryMethod qm = new QueryMethod(Repo.class.getMethod("findBy", Pageable.class), metadataMock,
			projectionFactoryMock);

	KeyValuePartTreeQuery partTreeQuery = new KeyValuePartTreeQuery(qm, QueryMethodEvaluationContextProvider.DEFAULT,
			kvOpsMock, SpelQueryCreator.class);

	KeyValueQuery<?> query = partTreeQuery.prepareQuery(new Object[] { PageRequest.of(2, 3) });

	assertThat(query.getOffset()).isEqualTo(6L);
	assertThat(query.getRows()).isEqualTo(3);
}
 
Example #3
Source File: KeyValuePartTreeQueryUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Test // DATAKV-142
@SuppressWarnings({ "unchecked", "rawtypes" })
public void shouldApplyDerivedMaxResultsToQueryWithParameters() throws SecurityException, NoSuchMethodException {

	when(metadataMock.getDomainType()).thenReturn((Class) Person.class);
	when(metadataMock.getReturnedDomainClass(any(Method.class))).thenReturn((Class) Person.class);

	QueryMethod qm = new QueryMethod(Repo.class.getMethod("findTop3ByFirstname", String.class), metadataMock,
			projectionFactoryMock);

	KeyValuePartTreeQuery partTreeQuery = new KeyValuePartTreeQuery(qm, QueryMethodEvaluationContextProvider.DEFAULT,
			kvOpsMock, SpelQueryCreator.class);

	KeyValueQuery<?> query = partTreeQuery.prepareQuery(new Object[] { "firstname" });

	assertThat(query.getCriteria()).isInstanceOf(SpelCriteria.class);
	assertThat(((SpelCriteria) query.getCriteria()).getExpression().getExpressionString())
			.isEqualTo("#it?.firstname?.equals([0])");
	assertThat(query.getRows()).isEqualTo(3);
}
 
Example #4
Source File: RepositoryQueryTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldSelectStringBasedNeo4jQueryForNamedQuery() {

	final String namedQueryName = "TestEntity.findAllByANamedQuery";
	when(namedQueries.hasQuery(namedQueryName)).thenReturn(true);
	when(namedQueries.getQuery(namedQueryName)).thenReturn("MATCH (n) RETURN n");

	final Neo4jQueryLookupStrategy lookupStrategy = new Neo4jQueryLookupStrategy(mock(Neo4jOperations.class),
		mock(
		Neo4jMappingContext.class), QueryMethodEvaluationContextProvider.DEFAULT);

	RepositoryQuery query = lookupStrategy
		.resolveQuery(queryMethod("findAllByANamedQuery"), TEST_REPOSITORY_METADATA,
			PROJECTION_FACTORY, namedQueries);
	assertThat(query).isInstanceOf(StringBasedNeo4jQuery.class);
}
 
Example #5
Source File: RepositoryQueryTest.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void shouldBindParameters() {

	Neo4jQueryMethod method = RepositoryQueryTest
		.neo4jQueryMethod("annotatedQueryWithValidTemplate", String.class, String.class);

	StringBasedNeo4jQuery repositoryQuery = spy(StringBasedNeo4jQuery.create(mock(Neo4jOperations.class),
		mock(Neo4jMappingContext.class), QueryMethodEvaluationContextProvider.DEFAULT,
		method));

	// skip conversion
	doAnswer(invocation -> invocation.getArgument(0)).when(repositoryQuery).convertParameter(any());

	Map<String, Object> resolveParameters = repositoryQuery
		.bindParameters(new Neo4jParameterAccessor(
			(Neo4jParameters) method.getParameters(), new Object[] { "A String", "Another String" }));

	assertThat(resolveParameters)
		.containsEntry("0", "A String")
		.containsEntry("1", "Another String");
}
 
Example #6
Source File: ArangoRepositoryFactory.java    From spring-data with Apache License 2.0 6 votes vote down vote up
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(
		final QueryLookupStrategy.Key key, final QueryMethodEvaluationContextProvider evaluationContextProvider) {

	QueryLookupStrategy strategy = null;
	switch (key) {
	case CREATE_IF_NOT_FOUND:
		strategy = new DefaultArangoQueryLookupStrategy(arangoOperations);
		break;
	case CREATE:
		break;
	case USE_DECLARED_QUERY:
		break;
	}
	return Optional.ofNullable(strategy);
}
 
Example #7
Source File: KeyValuePartTreeQueryUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Test // DATAKV-115
@SuppressWarnings({ "unchecked", "rawtypes" })
public void spelExpressionAndContextShouldNotBeReused() throws NoSuchMethodException, SecurityException {

	when(metadataMock.getDomainType()).thenReturn((Class) Person.class);
	when(metadataMock.getReturnedDomainClass(any(Method.class))).thenReturn((Class) Person.class);

	QueryMethod qm = new QueryMethod(Repo.class.getMethod("findByFirstname", String.class), metadataMock,
			projectionFactoryMock);

	KeyValuePartTreeQuery query = new KeyValuePartTreeQuery(qm, QueryMethodEvaluationContextProvider.DEFAULT, kvOpsMock,
			SpelQueryCreator.class);

	Object[] args = new Object[] { "foo" };

	Object first = query.prepareQuery(args).getCriteria();
	Object second = query.prepareQuery(args).getCriteria();

	assertThat(first).isNotSameAs(second);
}
 
Example #8
Source File: CachingKeyValuePartTreeQueryUnitTests.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Test // DATAKV-137
public void cachedSpelExpressionShouldBeReusedWithNewContext() throws NoSuchMethodException, SecurityException {

	QueryMethod qm = new QueryMethod(Repo.class.getMethod("findByFirstname", String.class), metadataMock,
			projectionFactoryMock);

	KeyValuePartTreeQuery query = new CachingKeyValuePartTreeQuery(qm, QueryMethodEvaluationContextProvider.DEFAULT,
			kvOpsMock, SpelQueryCreator.class);

	Object[] args = new Object[] { "foo" };

	SpelCriteria first = (SpelCriteria) query.prepareQuery(args).getCriteria();
	SpelCriteria second = (SpelCriteria) query.prepareQuery(args).getCriteria();

	assertThat(first.getExpression()).isSameAs(second.getExpression());
	assertThat(first.getContext()).isNotSameAs(second.getContext());
}
 
Example #9
Source File: SpannerRepositoryFactory.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private QueryMethodEvaluationContextProvider delegateContextProvider(
		QueryMethodEvaluationContextProvider evaluationContextProvider) {
	return new QueryMethodEvaluationContextProvider() {
		@Override
		public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
				T parameters, Object[] parameterValues) {
			StandardEvaluationContext evaluationContext = (StandardEvaluationContext) evaluationContextProvider
					.getEvaluationContext(parameters, parameterValues);
			evaluationContext
					.setRootObject(SpannerRepositoryFactory.this.applicationContext);
			evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
			evaluationContext.setBeanResolver(new BeanFactoryResolver(
					SpannerRepositoryFactory.this.applicationContext));
			return evaluationContext;
		}
	};
}
 
Example #10
Source File: SpannerQueryLookupStrategyTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Before
public void initMocks() {
	this.spannerMappingContext = new SpannerMappingContext();
	this.spannerTemplate = mock(SpannerTemplate.class);
	this.queryMethod = mock(SpannerQueryMethod.class);
	this.evaluationContextProvider = mock(QueryMethodEvaluationContextProvider.class);
	this.spelExpressionParser = new SpelExpressionParser();
	this.spannerQueryLookupStrategy = getSpannerQueryLookupStrategy();

	when(this.queryMethod.getQueryAnnotation()).thenReturn(new Query() {
		@Override
		public Class<? extends Annotation> annotationType() {
			return Query.class;
		}

		@Override
		public String value() {
			return "";
		}

		@Override
		public boolean dmlStatement() {
			return false;
		}
	});
}
 
Example #11
Source File: KeyValueRepositoryFactory.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * @param key
 * @param evaluationContextProvider
 * @param keyValueOperations
 * @param queryCreator
 * @since 1.1
 */
public KeyValueQueryLookupStrategy(@Nullable Key key,
		QueryMethodEvaluationContextProvider evaluationContextProvider, KeyValueOperations keyValueOperations,
		Class<? extends AbstractQueryCreator<?, ?>> queryCreator,
		Class<? extends RepositoryQuery> repositoryQueryType) {

	Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");
	Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!");
	Assert.notNull(queryCreator, "Query creator type must not be null!");
	Assert.notNull(repositoryQueryType, "RepositoryQueryType type must not be null!");

	this.evaluationContextProvider = evaluationContextProvider;
	this.keyValueOperations = keyValueOperations;
	this.queryCreator = queryCreator;
	this.repositoryQueryType = repositoryQueryType;
}
 
Example #12
Source File: HazelcastQueryLookupStrategy.java    From spring-data-hazelcast with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Required constructor, capturing arguments for use in {@link #resolveQuery}.
 * </P>
 * <p>
 * Assertions copied from {@link KayValueRepositoryFactory.KeyValueQUeryLookupStrategy} which this class essentially
 * duplicates.
 * </P>
 *
 * @param key                       Not used
 * @param evaluationContextProvider For evaluation of query expressions
 * @param keyValueOperations        Bean to use for Key/Value operations on Hazelcast repos
 * @param queryCreator              Likely to be {@link HazelcastQueryCreator}
 * @param hazelcastInstance         Instance of Hazelcast
 */
public HazelcastQueryLookupStrategy(QueryLookupStrategy.Key key,
                                    QueryMethodEvaluationContextProvider evaluationContextProvider,
                                    KeyValueOperations keyValueOperations,
                                    Class<? extends AbstractQueryCreator<?, ?>> queryCreator,
                                    HazelcastInstance hazelcastInstance) {

    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");
    Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!");
    Assert.notNull(queryCreator, "Query creator type must not be null!");
    Assert.notNull(hazelcastInstance, "HazelcastInstance must not be null!");

    this.evaluationContextProvider = evaluationContextProvider;
    this.keyValueOperations = keyValueOperations;
    this.queryCreator = queryCreator;
    this.hazelcastInstance = hazelcastInstance;
}
 
Example #13
Source File: EbeanQueryLookupStrategy.java    From spring-data-ebean with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link QueryLookupStrategy} for the given {@link EbeanServer} and {@link Key}.
 *
 * @param ebeanServer               must not be {@literal null}.
 * @param key                       may be {@literal null}.
 * @param evaluationContextProvider must not be {@literal null}.
 * @return
 */
public static QueryLookupStrategy create(EbeanServer ebeanServer, Key key,
                                         QueryMethodEvaluationContextProvider evaluationContextProvider) {

    Assert.notNull(ebeanServer, "EbeanServer must not be null!");
    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");

    switch (key != null ? key : Key.CREATE_IF_NOT_FOUND) {
        case CREATE:
            return new CreateQueryLookupStrategy(ebeanServer);
        case USE_DECLARED_QUERY:
            return new DeclaredQueryLookupStrategy(ebeanServer, evaluationContextProvider);
        case CREATE_IF_NOT_FOUND:
            return new CreateIfNotFoundQueryLookupStrategy(ebeanServer, new CreateQueryLookupStrategy(ebeanServer),
                    new DeclaredQueryLookupStrategy(ebeanServer, evaluationContextProvider));
        default:
            throw new IllegalArgumentException(String.format("Unsupported query lookup strategy %s!", key));
    }
}
 
Example #14
Source File: NativeEbeanUpdate.java    From spring-data-ebean with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link NativeEbeanUpdate} encapsulating the query annotated on the given {@link EbeanQueryMethod}.
 *
 * @param method                    must not be {@literal null}.
 * @param ebeanServer               must not be {@literal null}.
 * @param queryString               must not be {@literal null} or empty.
 * @param evaluationContextProvider
 */
public NativeEbeanUpdate(EbeanQueryMethod method, EbeanServer ebeanServer, String queryString,
                         QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(method, ebeanServer, queryString, evaluationContextProvider, parser);

    Parameters<?, ?> parameters = method.getParameters();
    boolean hasPagingOrSortingParameter = parameters.hasPageableParameter() || parameters.hasSortParameter();
    boolean containsPageableOrSortInQueryExpression = queryString.contains("#pageable")
            || queryString.contains("#sort");

    if (hasPagingOrSortingParameter && !containsPageableOrSortInQueryExpression) {
        throw new InvalidEbeanQueryMethodException(
                "Cannot use native queries with dynamic sorting and/or pagination in method " + method);
    }
}
 
Example #15
Source File: DatastoreRepositoryFactory.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
private QueryMethodEvaluationContextProvider delegateContextProvider(
		QueryMethodEvaluationContextProvider evaluationContextProvider) {
	return new QueryMethodEvaluationContextProvider() {
		@Override
		public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
				T parameters, Object[] parameterValues) {
			StandardEvaluationContext evaluationContext = (StandardEvaluationContext)
					evaluationContextProvider
					.getEvaluationContext(parameters, parameterValues);
			evaluationContext.setRootObject(
					DatastoreRepositoryFactory.this.applicationContext);
			evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
			evaluationContext.setBeanResolver(new BeanFactoryResolver(
					DatastoreRepositoryFactory.this.applicationContext));
			return evaluationContext;
		}
	};
}
 
Example #16
Source File: KeyValueRepositoryFactory.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
		NamedQueries namedQueries) {

	QueryMethod queryMethod = new QueryMethod(method, metadata, factory);

	Constructor<? extends KeyValuePartTreeQuery> constructor = (Constructor<? extends KeyValuePartTreeQuery>) ClassUtils
			.getConstructorIfAvailable(this.repositoryQueryType, QueryMethod.class,
					QueryMethodEvaluationContextProvider.class, KeyValueOperations.class, Class.class);

	Assert.state(constructor != null,
			String.format(
					"Constructor %s(QueryMethod, EvaluationContextProvider, KeyValueOperations, Class) not available!",
					ClassUtils.getShortName(this.repositoryQueryType)));

	return BeanUtils.instantiateClass(constructor, queryMethod, evaluationContextProvider, this.keyValueOperations,
			this.queryCreator);
}
 
Example #17
Source File: IgniteRepositoryFactory.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected Optional<QueryLookupStrategy> getQueryLookupStrategy(final QueryLookupStrategy.Key key,
    QueryMethodEvaluationContextProvider evaluationContextProvider) {
    return Optional.of((mtd, metadata, factory, namedQueries) -> {
        final Query annotation = mtd.getAnnotation(Query.class);
        final Ignite ignite = repoToIgnite.get(metadata.getRepositoryInterface());

        if (annotation != null && (StringUtils.hasText(annotation.value()) || annotation.textQuery() || annotation
            .dynamicQuery())) {

            String qryStr = annotation.value();

            boolean annotatedIgniteQuery = !annotation.dynamicQuery() && (StringUtils.hasText(qryStr) || annotation
                .textQuery());

            IgniteQuery query = annotatedIgniteQuery ? new IgniteQuery(qryStr,
                !annotation.textQuery() && (isFieldQuery(qryStr) || annotation.forceFieldsQuery()),
                annotation.textQuery(), false, IgniteQueryGenerator.getOptions(mtd)) : null;

            if (key != QueryLookupStrategy.Key.CREATE) {
                return new IgniteRepositoryQuery(ignite, metadata, query, mtd, factory,
                    getRepositoryCache(metadata.getRepositoryInterface()),
                    annotatedIgniteQuery ? DynamicQueryConfig.fromQueryAnnotation(annotation) : null,
                    evaluationContextProvider);
            }
        }

        if (key == QueryLookupStrategy.Key.USE_DECLARED_QUERY) {
            throw new IllegalStateException("To use QueryLookupStrategy.Key.USE_DECLARED_QUERY, pass "
                + "a query string via org.apache.ignite.springdata22.repository"
                + ".config.Query annotation.");
        }

        return new IgniteRepositoryQuery(ignite, metadata, IgniteQueryGenerator.generateSql(mtd, metadata), mtd,
            factory, getRepositoryCache(metadata.getRepositoryInterface()),
            DynamicQueryConfig.fromQueryAnnotation(annotation), evaluationContextProvider);
    });
}
 
Example #18
Source File: SqlSpannerQueryTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Before
public void initMocks() throws NoSuchMethodException {
	this.queryMethod = mock(SpannerQueryMethod.class);
	// this is a dummy object. it is not mockable otherwise.
	Method method = Object.class.getMethod("toString");
	when(this.queryMethod.getMethod()).thenReturn(method);
	when(this.spannerEntityProcessor.getWriteConverter()).thenReturn(new SpannerWriteConverter());
	this.spannerTemplate = spy(new SpannerTemplate(() -> this.databaseClient,
			this.spannerMappingContext, this.spannerEntityProcessor,
			mock(SpannerMutationFactory.class), new SpannerSchemaUtils(
					this.spannerMappingContext, this.spannerEntityProcessor, true)));
	this.expressionParser = new SpelExpressionParser();
	this.evaluationContextProvider = mock(QueryMethodEvaluationContextProvider.class);
}
 
Example #19
Source File: ReactiveAggregateQuerySupportingRepositoryFactory.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<QueryLookupStrategy> getQueryLookupStrategy(QueryLookupStrategy.Key key,
                                                            QueryMethodEvaluationContextProvider evaluationContextProvider) {

  Optional<QueryLookupStrategy> parentQueryLookupStrategy = super.getQueryLookupStrategy(key, evaluationContextProvider);
  Assert.isTrue(parentQueryLookupStrategy.isPresent(), "Expecting parent query lookup strategy to be present");
  return Optional.of(new AggregateQueryLookupStrategy(parentQueryLookupStrategy.get()));
}
 
Example #20
Source File: MybatisRepositoryFactory.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key,
		QueryMethodEvaluationContextProvider evaluationContextProvider) {

	return Optional.of(MybatisQueryLookupStrategy.create(sqlSessionTemplate, key,
			evaluationContextProvider));
}
 
Example #21
Source File: RepositoryQueryTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldDetectInvalidAnnotation() {

	Neo4jQueryMethod method = neo4jQueryMethod("annotatedQueryWithoutTemplate");
	assertThatExceptionOfType(MappingException.class)
		.isThrownBy(
			() -> StringBasedNeo4jQuery.create(mock(Neo4jOperations.class), mock(Neo4jMappingContext.class),
				QueryMethodEvaluationContextProvider.DEFAULT, method))
		.withMessage("Expected @Query annotation to have a value, but it did not.");
}
 
Example #22
Source File: NonReactiveAggregateQuerySupportingRepositoryFactory.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<QueryLookupStrategy> getQueryLookupStrategy(@Nullable QueryLookupStrategy.Key key,
                                                            QueryMethodEvaluationContextProvider evaluationContextProvider) {

  Optional<QueryLookupStrategy> parentQueryLookupStrategy = super.getQueryLookupStrategy(key, evaluationContextProvider);
  Assert.isTrue(parentQueryLookupStrategy.isPresent(), "Expecting parent lookup strategy");
  return Optional.of(new AggregateQueryLookupStrategy(parentQueryLookupStrategy.get()));
}
 
Example #23
Source File: StringBasedNeo4jQuery.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link StringBasedNeo4jQuery} for a query method that is annotated with {@link Query @Query}. The annotation
 * is expected to have a value.
 *
 * @param neo4jOperations the Neo4j operations
 * @param mappingContext a Neo4jMappingContext instance
 * @param evaluationContextProvider a QueryMethodEvaluationContextProvider instance
 * @param queryMethod the query method
 * @return A new instance of a String based Neo4j query.
 */
static StringBasedNeo4jQuery create(Neo4jOperations neo4jOperations, Neo4jMappingContext mappingContext,
	QueryMethodEvaluationContextProvider evaluationContextProvider,
	Neo4jQueryMethod queryMethod) {

	Query queryAnnotation = queryMethod.getQueryAnnotation()
		.orElseThrow(() -> new MappingException("Expected @Query annotation on the query method!"));

	String cypherTemplate = Optional.ofNullable(queryAnnotation.value())
		.filter(StringUtils::hasText)
		.orElseThrow(() -> new MappingException("Expected @Query annotation to have a value, but it did not."));

	return new StringBasedNeo4jQuery(neo4jOperations, mappingContext, evaluationContextProvider, queryMethod,
		cypherTemplate, Neo4jQueryType.fromDefinition(queryAnnotation));
}
 
Example #24
Source File: KeyValuePartTreeQuery.java    From spring-data-keyvalue with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link KeyValuePartTreeQuery} for the given {@link QueryMethod}, {@link EvaluationContextProvider},
 * {@link KeyValueOperations} using the given {@link QueryCreatorFactory} producing the {@link AbstractQueryCreator}
 * in charge of altering the query.
 *
 * @param queryMethod must not be {@literal null}.
 * @param evaluationContextProvider must not be {@literal null}.
 * @param keyValueOperations must not be {@literal null}.
 * @param queryCreatorFactory must not be {@literal null}.
 * @since 2.0
 */
public KeyValuePartTreeQuery(QueryMethod queryMethod, QueryMethodEvaluationContextProvider evaluationContextProvider,
		KeyValueOperations keyValueOperations, QueryCreatorFactory queryCreatorFactory) {

	Assert.notNull(queryMethod, "Query method must not be null!");
	Assert.notNull(evaluationContextProvider, "EvaluationContextprovider must not be null!");
	Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!");
	Assert.notNull(queryCreatorFactory, "QueryCreatorFactory type must not be null!");

	this.queryMethod = queryMethod;
	this.keyValueOperations = keyValueOperations;
	this.evaluationContextProvider = evaluationContextProvider;
	this.queryCreatorFactory = queryCreatorFactory;
}
 
Example #25
Source File: SpelExpressionStringQueryParameterBinder.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SpelExpressionStringQueryParameterBinder}.
 *
 * @param parameters                must not be {@literal null}
 * @param values                    must not be {@literal null}
 * @param query                     must not be {@literal null}
 * @param evaluationContextProvider must not be {@literal null}
 * @param parser                    must not be {@literal null}
 */
public SpelExpressionStringQueryParameterBinder(DefaultParameters parameters, Object[] values, StringQuery query,
                                                QueryMethodEvaluationContextProvider evaluationContextProvider, SpelExpressionParser parser) {

    super(parameters, values, query);
    Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!");
    Assert.notNull(parser, "SpelExpressionParser must not be null!");

    this.evaluationContextProvider = evaluationContextProvider;
    this.query = query;
    this.parser = parser;
}
 
Example #26
Source File: ReactiveStringBasedNeo4jQuery.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link ReactiveStringBasedNeo4jQuery} for a query method that is annotated with {@link Query @Query}. The annotation
 * is expected to have a value.
 *
 * @param neo4jOperations reactive Neo4j operations
 * @param mappingContext a Neo4jMappingContext instance
 * @param evaluationContextProvider a QueryMethodEvaluationContextProvider instance
 * @param queryMethod the query method
 * @return A new instance of a String based Neo4j query.
 */
static ReactiveStringBasedNeo4jQuery create(ReactiveNeo4jOperations neo4jOperations, Neo4jMappingContext mappingContext,
	QueryMethodEvaluationContextProvider evaluationContextProvider,
	Neo4jQueryMethod queryMethod) {

	Query queryAnnotation = queryMethod.getQueryAnnotation()
		.orElseThrow(() -> new MappingException("Expected @Query annotation on the query method!"));

	String cypherTemplate = Optional.ofNullable(queryAnnotation.value())
		.filter(StringUtils::hasText)
		.orElseThrow(() -> new MappingException("Expected @Query annotation to have a value, but it did not."));

	return new ReactiveStringBasedNeo4jQuery(neo4jOperations, mappingContext, evaluationContextProvider, queryMethod,
		cypherTemplate, Neo4jQueryType.fromDefinition(queryAnnotation));
}
 
Example #27
Source File: StringBasedNeo4jQuery.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
private StringBasedNeo4jQuery(Neo4jOperations neo4jOperations,
	Neo4jMappingContext mappingContext, QueryMethodEvaluationContextProvider evaluationContextProvider,
	Neo4jQueryMethod queryMethod, String cypherTemplate, Neo4jQueryType queryType) {

	super(neo4jOperations, mappingContext, queryMethod, queryType);

	SpelExtractor spelExtractor = SPEL_QUERY_CONTEXT.parse(cypherTemplate);
	this.spelEvaluator = new SpelEvaluator(evaluationContextProvider, queryMethod.getParameters(), spelExtractor);
	this.cypherQuery = spelExtractor.getQueryString();
}
 
Example #28
Source File: RepositoryQueryTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldSelectStringBasedNeo4jQuery() {

	final Neo4jQueryLookupStrategy lookupStrategy = new Neo4jQueryLookupStrategy(mock(Neo4jOperations.class),
		mock(
		Neo4jMappingContext.class), QueryMethodEvaluationContextProvider.DEFAULT);

	RepositoryQuery query = lookupStrategy
		.resolveQuery(queryMethod("annotatedQueryWithValidTemplate"), TEST_REPOSITORY_METADATA,
			PROJECTION_FACTORY, namedQueries);
	assertThat(query).isInstanceOf(StringBasedNeo4jQuery.class);
}
 
Example #29
Source File: Neo4jQueryLookupStrategy.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
public Neo4jQueryLookupStrategy(Neo4jOperations neo4jOperations,
	Neo4jMappingContext mappingContext,
	QueryMethodEvaluationContextProvider evaluationContextProvider) {
	this.neo4jOperations = neo4jOperations;
	this.mappingContext = mappingContext;
	this.evaluationContextProvider = evaluationContextProvider;
}
 
Example #30
Source File: HazelcastRepositoryFactory.java    From spring-data-hazelcast with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Ensure the mechanism for query evaluation is Hazelcast specific, as the original
 * {@link KeyValueRepositoryFactory.KeyValueQueryLookupStrategy} does not function correctly for Hazelcast.
 * </P>
 */
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(QueryLookupStrategy.Key key,
                                                        QueryMethodEvaluationContextProvider evaluationContextProvider) {
    return Optional.of(new HazelcastQueryLookupStrategy(key, evaluationContextProvider, keyValueOperations, queryCreator,
            hazelcastInstance));
}